Parsing integers from a line

12,355

Solution 1

If the only thing in there is whitespace and integers, just try something like this:

int i1, i2;
stringstream ss(lineFromGetLine);
ss >> i1 >> i2;

or easier:

int i1, i2;
theFileStream >> i1 >> i2;

Solution 2

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.

while(inFile >> rows >> columns)
{
    // Successfully read rows and columns

    // Now remove the extra stuff on the line you do not want.
    inFile.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}

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

while(inFile.eof())

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.

while(inFile.eof())  // Should probably test good()
{
    getLine(inFile,inputline);
    if(inFile.eof()) // should probably test good()
    {
         break;
    }
}
Share:
12,355
Tomek
Author by

Tomek

Updated on August 28, 2022

Comments

  • Tomek
    Tomek over 1 year

    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.

  • Admin
    Admin over 13 years
    You must not test good() and instead test fail(), which is same condition (except reversed) that while (stream) tests.
  • Martin York
    Martin York over 13 years
    @Roget Pate: If fail() is the inverse of good() why can we test good()?
  • Yoda
    Yoda almost 12 years
    how to DO IT for string not char*
  • mekanik
    mekanik almost 12 years
    @Robert: I have no idea what your complaint is. You can construct a stringstream from a char* just as easily as from a std::string. If you have a different question, ask a new one. But don't down-vote random answers.