如何将 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("%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。
相关文章:
- void* 数组将元素转换为另一种类型
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 将字符串元素转换为整数 (C++11)
- 使用Stoi()将字符串数组元素转换为C 中的INT
- 如何将双数组的单个元素转换为 QString
- 向量的第一个元素转换器值
- 将字符串元素转换为整数C++
- 类型转换问题:字符数组的元素转换为整数变量
- 将文件一行的每个元素转换为整数
- 如何在C++visual studio 2013中将列表元素转换为文本块
- C++:如何将字符串矢量元素转换为无符号字符
- 如何将 c++ 字符串对象的元素转换为浮点数
- 希望我的代码逐行将矩阵元素转换为向量,它只将矩阵的最后一行显示为向量
- 将vector元素转换为字符串进行比较
- 将<char>向量前 N 个元素转换为整数
- 如何在C++中将字符串中的元素转换为它自己的字符串?
- 将uint8 vector类型的元素转换为stringstream类型
- 如何将两个双数据类型元素转换为一个Point数据类型
- 将CSringArray中的其他字符串元素转换为int - mfcc++
- 将字符数组的元素转换为整数,并使用cout打印