Search code examples
c++ifstreameol

c++ ifstream, detect if letter or EOLine?


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;
    }

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' );