Search code examples
c++stringatof

How to convert an element of a c++ string object to a float


The goal is to parse out floating point numbers from a (string) expression and store them into a vector of floats. I am currently trying to convert the number substring to a character array with c_str() and then use the atof() function. This is resulting in a seg fault. Any suggestions on how to make this conversion? Thank you.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>

using namespace std;

int parse_expression(string expression, vector<char>& op, vector<float>& num){
    int i = 0;
    int n = 0;
    int o = 0;
    string num_string;

    const char * expr = expression.c_str();
    printf("%s\n", expr);
    for(i=0; i<expression.size()-1; i++){
        //Handle Spaces
        if(expr[i] != ' '){
            //Handle operatorsr
            if(expr[i] == '+' || expr[i] == '-' || expr[i] == '/' || expr[i] == '*'){
                printf("operator\n");
                op[o] = expr[i];
                o++;
            }
            //Handle numbers
            else{
                printf("Handling nums\n");
                while(expr[i] != ' '){
                    printf("%c", expr[i]);
                    num_string += expr[i];
                    i++;
                }
                i--;
                cout << num_string << endl;
                printf("test1\n");
                printf("%s", x);
                num[n] = atof(num_string.c_str());
                n++;
            }
        }
        //Reset flag if space encountered
        else{
            printf("space\n");
        }
    }

    return n;
}
int main(){
    vector<float> nums;
    vector<char> operators;
    parse_expression("5.0 + 45.0 - 23.0 * 24.0 / 3.0 - 12.0 + 1.0", operators, nums);
    return 0;

}

Solution

  • You should push_back to increase the size of the array:

    op.push_back(expr[i]);
    num.push_back(atof(num_string.c_str()));
    

    You don't need variables n and o.