seekg() before each .get() call VS seekg() before for loop

66 Views Asked by At

I am just trying to read simple text file with ifstream. Suppose my text file looks like this (I don't know how to properly format it here, so here is how I wrote it notepad): a\tb\nc\t\d\n

Output from reading text file using .seekg() before each .get() differs from output when .seekg() is called only before for loop (see output).

Question:

Is this expected behaviour? If yes then why is it happening?

Code:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{

    ifstream myfile("test.txt");
    if (myfile)
    {

        cout << "Using seekg before each myfile.get():" << endl;
        cout << "***********************" << endl;
        myfile.seekg(0);
        cout << (char)myfile.get();
        myfile.seekg(1);
        cout << (char)myfile.get();
        myfile.seekg(2);
        cout << (char)myfile.get();
        myfile.seekg(3);
        cout << (char)myfile.get();
        myfile.seekg(4);
        cout << (char)myfile.get() << endl;
        cout << "***********************" << endl;

        cout << "Using seekg only before loop:" << endl;
        cout << "***********************" << endl;
        myfile.seekg(0);
        for (int i = 0; i <= 4; i++)
        {
            cout << (char)myfile.get();
        }
        cout << endl;
        cout << "***********************" << endl;

        myfile.close();
    }

}

Output:

Output after running above code

After debugging:

In text file:

  • a is at position 0
  • '\t' is at position 1
  • b is at position 2
  • when .seekg(3) is used right before .get() then .get() returns '\n'
  • when .seekg(4) is used right before .get() then .get() returns '\n' also
  • when .seekg(0) is used only before for loop (see code) then .get() only returns single '\n' at position 3/4 , meaning '\n' is at the position 3 and 'c' is at position 4
0

There are 0 best solutions below