Search code examples
c++string-parsing

C++ Parse line of doubles of variable length


I am trying to read in a file line by line, parse it based on spaces and place it into a vector called input. However, I cannot do a cin >> x1 >> x2 >> x3 ... because the line doesn't have a set number of terms. Below is what I was thinking, but it could be wrong.

vector <double> input;
fstream inputFile("../Sphere.in", fstream::in);
inputFile.open("../Sphere.in", fstream::in);

while (inputFile.good())
{
    getline(inputFile, line);

then something in here that says for each space in line put in input[i]

 }

I am very new at C++ and would appreciate any help that someone could throw my way.

Thanks,

John


Solution

  • while (inputFile.good()) is wrong, as it only evaluates to false after a read fails. Without additional checks inside the loop, the last iteration will work on invalid input. The correct, idiomatic way is to put the read in loop's condition:

    while (getline(inputFile, line)) { ... }
    

    This way you only enter the loop if getline succeeds. Now you can construct a string stream from line and read doubles from there, using similar approach with read inside loop condition:

    while (getline(inputFile, line)) {
        istringstream iss(line);
        double d;
        while (iss >> d) input.push_back(d);
    }