Sean Lau
Sean Lau

Reputation: 43

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?

Upvotes: 4

Views: 174

Answers (2)

einpoklum
einpoklum

Reputation: 131554

Your question regards a semantic ambiguity with std::getline(): Should it result be "a line", in which case the result should include the line-ending newline character, or should the result be the contents of a line, in which case the trailing newline should be dropped?

In the C programming language, getline() takes the first approach:

getline() reads an entire line from stream ... The [result] buffer is null-terminated and includes the newline character, if one was found.

but in C++, the semantics are different: The newline is considered to be a delimiter, and the results of repeated calls to std::getline() is the content without the delimiter. Note that the function actually takes the delimiter in a third parameter, which defaults to '\n', but could be replaced with any other single character. That makes std::getline() more of a tokenizer.

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249153

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.

Upvotes: 2

Related Questions