0
C++ Question
Hello everyone, I have this code (https://code.sololearn.com/cZArRSUR293A/#cpp) and I want to cout all the content of the txt file but it only prints the first line, how can I print it all? Thank you for reading this anyway :-)
3 Answers
+ 2
Replace this:
getline(marchaPeronista, letraMP);
with:
string tmp;
while(getline(marchaPeronista, tmp)) {
letraMP = letraMP + tmp + "\n";
}
+ 1
getLine(istream &is, string &s) returns istream, that was passed to it. Because of this ( http://www.cplusplus.com/reference/ios/ios/operator_bool/ ) operator, testing a stream returns true, if the stream is in good condition (can read), and false if it's in the 'fail' state. So, basically, we are reading a line into the temporary string 'tmp' until 'marchaPeronista' gets into the 'fail' state. And that 'fail' would happen either if it reaches the EOF character, or if any other error occurs. So in that loop, each string will be read to the end of the file, or the reading would stop, if an error occurs. In the loop body we're appending the freshly read 'tmp' string to 'letraMP', adding "\n" to the end (readline doesn't read the actual newLine).
And yeah, some documentation links:
http://www.cplusplus.com/reference/string/string/getline/
http://www.cplusplus.com/reference/istream/istream/
http://www.cplusplus.com/reference/ios/ios/operator_bool/
0
Thanks!! Can you explain me how this works? If its not an issue