Search code examples
c++c++11iostreamgetline

Why do I need std::endl to reproduce input lines I got with getline()?


I am a newbie learning C++ to read or write from a file. I searched how to read all contents from a file and got the answer I can use a while loop.

string fileName = "data.txt";
string line ;
ifstream myFile ;
myFile.open(fileName);
while(getline(myFile,line)){
    cout << line << endl;
}

data.txt has three lines of content and output as below.

Line 1
Line 2
Line 3

but if I remove "endl" and only use cout<<line; in the curly bracket of the while loop, the output change to :

 Line 1Line 2Line 3

From my understanding, the while loop was executed 3 times, what's the logic behind it?


Solution

  • endl means "end line" and it does two things:

    1. Move the output cursor to the next line.
    2. Flush the output, in case you're writing to a file this means the file will be updated right away.

    By removing endl you are writing all the input lines onto a single output line, because you never told cout to go to the next line.