ifstream's operator>> to detect end of line?

Bonk picture Bonk · Jul 27, 2011 · Viewed 11.2k times · Source

I have an irregular list where the data look like this:

[Number] [Number]
[Number] [Number] [Number] 
[Number] [Number] [Number] 
[Number] [Number] [Number] 
[Number] [Number] [Number] 
[...]

Notice that some lines have 2 numbers, some have 3 numbers. Currently I have my input code look like these

inputFile >> a >> b >> c;

However, I want to it ignore lines with only 2 numbers, is there a simple work around for this? (preferably without using string manipulations and conversions)

Thanks

Answer

Martin York picture Martin York · Jul 27, 2011

Use getline and then parse each line seprately:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string   line;
    while(std::getline(std::cin, line))
    {
        std::stringstream linestream(line);
        int a;
        int b;
        int c;
        if (linestream >> a >> b >> c)
        {
            // Three values have been read from the line
        }
    }
}