Как преобразовать элемент строкового объекта c ++ в число с плавающей точкой

Цель состоит в том, чтобы разобрать числа с плавающей запятой из (строкового) выражения и сохранить их в векторе чисел с плавающей запятой. В настоящее время я пытаюсь преобразовать числовую подстроку в массив символов с помощью 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;

}

-1

Решение

Вы должны нажать push_back, чтобы увеличить размер массива:

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

Вам не нужны переменные n и o.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector