如何将 c++ 字符串对象的元素转换为浮点数

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

本文关键字:元素 转换 浮点数 对象 c++ 字符串      更新时间:2023-10-16

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

#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("%sn", 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("operatorn");
                op[o] = expr[i];
                o++;
            }
            //Handle numbers
            else{
                printf("Handling numsn");
                while(expr[i] != ' '){
                    printf("%c", expr[i]);
                    num_string += expr[i];
                    i++;
                }
                i--;
                cout << num_string << endl;
                printf("test1n");
                printf("%s", x);
                num[n] = atof(num_string.c_str());
                n++;
            }
        }
        //Reset flag if space encountered
        else{
            printf("spacen");
        }
    }
    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;
}
您应该

push_back增加数组的大小:

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

您不需要变量 n 和 o。