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
Just use std::getline or alternatively check for '\n' character. For sure, '\n' is the end of line character.
You can use peek() : if (infile. peek()!
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.
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.
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
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With