7

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

Mat
  • 202,337
  • 40
  • 393
  • 406
Bonk
  • 1,859
  • 9
  • 28
  • 46

3 Answers3

13

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
        }
    }
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
4

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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
2
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!
      }
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
Nawaz
  • 353,942
  • 115
  • 666
  • 851