Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 779
Bonk Avatar asked Jul 27 '11 19:07

Bonk


People also ask

How do you find the end of a line in C++?

Just use std::getline or alternatively check for '\n' character. For sure, '\n' is the end of line character.

How do you check if a file has a next line C++?

You can use peek() : if (infile. peek()!

Does Getline go to the next line?

getline(cin, newString); begins immediately reading and collecting characters into newString and continues until a newline character is encountered. The newline character is read but not stored in newString.

How do you read one line at a time in C++?

To read the file contents one line at a time, we will use the 'getline() ' function. The getline() function has two different signatures. In the first signature, the function takes the stream object as the first parameter and a string as the second parameter.


2 Answers

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
        }
    }
}
like image 75
Martin York Avatar answered Sep 29 '22 03:09

Martin York


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.

like image 25
Fred Foo Avatar answered Sep 29 '22 05:09

Fred Foo