Bonk
Bonk

Reputation: 1949

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

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

Upvotes: 7

Views: 12009

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361252

std::string line;
while(std::getline(inputFile, line))
{
      std::stringstream ss(line);
      if ( ss >> a >> b >> c)
      {
           // line has three numbers. Work with this!
      }
      else
      {
           // line does not have three numbers. Ignore this case!
      }
}

Upvotes: 2

Loki Astari
Loki Astari

Reputation: 264331

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
        }
    }
}

Upvotes: 13

Fred Foo
Fred Foo

Reputation: 363487

The simplest solution I can think of is to read the file line-by-line with std::getline, then store each line in turn in an std::istringstream, then do >> a >> b >> c on that and check the return value.

Upvotes: 4

Related Questions