Reading text file line by line


What is the best practice to read text file line by line in the loop into std:string variable?


The best practice is to use std::getline() in a loop:

for (std::string line; std::getline(input_file, line);)
    // work with `line`

Using the stream input operation as the condition of the loop is the easiest way to “automatically” handle input failure and EOF (end-of-file).

Having said this, I recommend you join the CPlusPlus forum for this sort of beginner questions:


Thank you Андрей. It is possible to read through SDL_RWops? Read line by line from SDL_RWops?


My mistake, in my previous post I believed you ask a general C++ question.
From what I can see in the SDL_RWops Wiki there exists no dedicated read-line function for text files.

You could read the text file entirely into memory as shown in the SDL_RWread example into a char buffer (such as std::vector<char>) then load the buffer into a std::strstream on which you use std::getline() as in shown in my previous reply.

Another idea, which doesn’t load the entire file into memory, is to read char-by-char into a std::string (use push_back) by using SDL_ReadU8() until you detect '\n' or "\r\n".

(BTW I am “andrei” after recovering my original account.)

EDIT: I hope you don’t have to use Unicode text files, or the above ideas won’t work.


Thank you. I will try 2 suggested ways and compare perfomance.
I do not use Unicode files. I use only single byte characters in my file.