I am parsing an input text file. If I grab the input one line at a time using getline(), is there a way that I can search through the string to get an integer? I was thinking something similar to getNextInt() in Java.
I know there has to be 2 numbers in that input line; however, these values will be separated by one or more white space characters, so I can't just go to a specific position.
I tried:
and I got the following error:
"term does not evaluate to a function taking 1 arguments" at line
ss(inputLine);
edit: so you have to declare the string stream at the moment you give it the paramater. Correctoed code edited above.
If the only thing in there is whitespace and integers, just try something like this:
or easier:
It's more than a little bit C-ish, but you could use sscanf() on the C string representation. Or you could use strtol() or relatives - also on the C string representation.
A more C++-ish way would probably use a string stream and an extractor.
Never use .eof() for testing whether you can read nor for testing whether the previous read failed. Both approaches will fail in certain situations because:
In general you should ONLY use .eof() after a failed read to check if the failure was caused by end of input.
Use
while (std::getline(...))
for looping over lines.There are a couple of things to consider:
Lets assume you have two numbers on each line followed by text you don't care about.
Also note if the only thing separating the integer values is "white space" then you don't even need to use the ignore() line.
The above while() works because: The operator >> returns a stream object (reference). Because the stream object is being used in a boolean context the compiler will try and convert it into a bool and the stream object has a cast operator that does that conversion (by calling good() on the stream).
The important thing to note is NOT to use the line
If you do use this then you fall into the trap of the last line problem. If you have read all the data eof() is still false (as it is not true until you try and read past EOF). So there is no data left in the file but you still enter the loop body. In your code the getline() is then executed and fails (no more data), EOF is now set. What the rest of the loop does will depend on how and where inLine is defined.
You can use this test as above. But you must also be willing to test the stream is OK after you have used it.