piggyback
piggyback

Reputation: 9254

Convert string from getline into a number

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?

Upvotes: 0

Views: 2555

Answers (1)

sam
sam

Reputation: 170

instead of using atof use the stringstream

while(!ss.eof())
{
    double number;
    ss>>number;
}

EDIT: I have updated your split function and removed the superfluous return.

void split(const string &s, vector<double> &elems) {
    stringstream ss(s);
    while (!ss.eof()) {
        double number;
        ss >> number;
        cout << number;
        elems.push_back(number);
    }

}

int main()
{
    std::vector<double> columns;
    split("1.32\t1.65\t1.98456\t2.34",columns);
    return 0;
}

Upvotes: 1

Related Questions