Reading string from the file and convert it to vector<double>

Hi,

I tried to read string from the file and convert it to a vector. But I don't know how to deal with decimal numbers. I also know how to use stod to convert one string decimal number.

Thanks!! Any suggestions?

Input (string, reading from the file): [-1, 2, 25, 3, 2]. (Okay with integers)

For example: [-1, 2.02, 25, 3.03, 2]
(it only outputs -1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    ifstream myFile("xxx.txt");
    string data;
    vector<double> dataNum;

    while (getline(myFile, data)) {
        data.erase(remove_if(data.begin(), data.end(), [](char c){return c == '[' || c == ']' || c == ',';}), data.end());

        int d = 0;
        stringstream ss(data);
        while (ss >> d) {
            dataNum.push_back(d);
        }

        for (int i = 0; i < dataNum.size(); i++) {
            cout << dataNum[i] << ' ';
        }
        cout << endl;
        dataNum.clear();
    }

    myFile.close();
Last edited on
int d = 0;
becomes
double d = 0;
Thank you so so so much.

It works!!
Topic archived. No new replies allowed.