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?
endl means "end line" and it does two things:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With