Convert string from getline into a number
- by haskellguy
I am trying to create a 2D array with vectors. I have a file that has for each line a set of numbers. So what I did I implemented a split function that every time I have a new number (separated by \t) it splits that and add it to the vector
vector<double> &split(const string &s, char delim, vector<double> &elems) {
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
cout << item << endl;
double number = atof(item.c_str());
cout << number;
elems.push_back(number);
}
return elems;
}
vector<double> split(const string &s, char delim) {
vector<double> elems;
split(s, delim, elems);
return elems;
}
After that I simply iterate through it.
int main()
{
ifstream file("./data/file.txt");
string row;
vector< vector<double> > matrix;
int line_count = -1;
while (getline(file, row)) {
line_count++;
if (line_count <= 4) continue;
vector<double> cols = split(row, '\t');
matrix.push_back(cols);
}
...
}
Now my issues is in this bit here:
while (getline(ss, item, delim)) {
cout << item << endl;
double number = atof(item.c_str());
cout << number;
Where item.c_str() is converted to a 0. Shouldn't that be still a string having the same value as item? It works on a separate example if I do straight from string to c_string, but when I use this getline I end up in this error situation,
hints?