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

Time:08-14

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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related