如何将 C++ 字符串对象的元素转换为浮点数
How to convert an element of a c++ string object to a float
目标是从(字符串)表达式中解析出浮点数并将它们存储到浮点向量中。我目前正在尝试使用 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("%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;
}
你应该push_back增加数组的大小:
op.push_back(expr[i]);
num.push_back(atof(num_string.c_str()));
您不需要变量 n 和 o。
目标是从(字符串)表达式中解析出浮点数并将它们存储到浮点向量中。我目前正在尝试使用 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("%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;
}
你应该push_back增加数组的大小:
op.push_back(expr[i]);
num.push_back(atof(num_string.c_str()));
您不需要变量 n 和 o。