C++ 如何转换c++;字符串对象到浮点

C++ 如何转换c++;字符串对象到浮点,c++,string,atof,C++,String,Atof,目标是从(字符串)表达式中解析出浮点数,并将它们存储到浮点向量中。我目前正在尝试使用c_str()将数字子字符串转换为字符数组,然后使用atof()函数。这将导致seg故障。关于如何进行这种转换有什么建议吗?多谢各位 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include &l

目标是从(字符串)表达式中解析出浮点数,并将它们存储到浮点向量中。我目前正在尝试使用c_str()将数字子字符串转换为字符数组,然后使用atof()函数。这将导致seg故障。关于如何进行这种转换有什么建议吗?多谢各位

#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;

}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int parse_表达式(字符串表达式、向量&op、向量&num){
int i=0;
int n=0;
INTO=0;
字符串num_字符串;
const char*expr=expression.c_str();
printf(“%s\n”,expr);

对于(i=0;i您应该向后推_以增加数组的大小:

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

您不需要变量n和o。

不要为不相关的语言添加标记!