Question

I have this function to read in all ints from the file. The problem is when i read letters i trigger a new line and i always seek by 1 and not to the end of line. How can i write this function better?

int v;
    while (!in.eof())
    {
        while (in >> v)
            cout << v << " ";

        cout << endl;
        if (in.eof())
            break;
        in.clear();
        in.seekg(1, ios::cur);
        int a;
        a=0;
    }
Was it helpful?

Solution

If your file consists of just ints separated by whitespace (including) newlines then this should be sufficient.

while( in >> v )
{
    // do something with v
}

After the file, if in.fail() is false and in.eof() is true, then you reached the end of the file without a formatting error. Otherwise an error reading an int occurred.

If you receive invalid input and want to recover from that then you need to work out how you want to recover. If you want to skip until the end of the line and start parsing again, you can use something like this.

in.clear();
in.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

OTHER TIPS

First problem the above code does not stop at the end of line.
The operator>>() ignores "White Space Characters" which includes the new line character.

How can this be written better?
That is hard to tell without knowing what you are trying to do with the numbers and what the input format of the file is!

But If I were writting this I would write it without using these lines:

    if (in.eof())
            break;
    in.clear();
    in.seekg(1, ios::cur);

When processing a formated text file it is rare to see the use of seek().

Assumign:
File contains just numbers.
You want to read all the numbers into a container.

std::vector<int>    data;

std::copy(  std::istream_iterator<int>(in),  // An iterator from current point
            std::istream_iterator<int>(),    // To end of file.
            std::inserter(data)              // Destination (insert into data)
         );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top