The loop
while (!in.eof()) {
text.append(s);
in >> s;
}
is wrong, because the condition while (!in.eof())
may be false
even when the previous statement in >> s
succeeded. It would be better to write while (!in.fail())
instead of while (!in.eof())
.
However, it would be clearer and slightly more efficient to write the loop like this:
while ( in >> s ) {
text.append(s);
}
This loop condition indirectly uses in.operator bool()
, which is equivalent to !in.fail()
.
The reason why this loop is a bit more efficient than the other loop is that in the first iteration of the other loop, an empty string was always appended. This is no longer the case in this loop.
Although you did not state this in the question, in the comments section of your question, you stated that it would be preferable for the whitespace characters to be retained instead of being discarded. In that case, you should not be using operator >>
for reading input, which reads one word at a time, but you should rather be using std::getline
, which reads one line at a time:
string Read(string& file) {
ifstream in;
string text;
string s;
in.open(file, ios::in);
while ( getline( in, s ) ) {
text.append( s );
text.append( "\n" );
}
return text;
}