Search code examples
c++ifstreamstringstreamgetlinefile-read

Read multiple strings from a file C++


I need to read different values stored in a file one by one. So I was thinking I can use ifstream to open the file, but since the file is set up in such a way that a line might contain three numbers, and the other line one number or two numbers I'm not sure how to read each number one by one. I was thinking of using stringstream but I'm not sure if that would work.

The file is a format like this.

52500.00       64029.50      56000.00
65500.00       
53780.00       77300.00     
44000.50       80100.20      90000.00      41000.00    
60500.50       72000.00

I need to read each number and store it in a vector.

What is the best way to accomplish this? Reading one number at a time even though each line contains a different amount of numbers?


Solution

  • Why not read them as numbers from the file?

    double temp;
    vector<double> vec;
    ifstream myfile ("file.txt");
    
    if (myfile.is_open()) {
      while ( myfile >> temp) {
        vec.push_back(temp);
      }
      myfile.close();
    }