How to read long lines from a text file in C ++?

I am using the following code to read lines from a text file. What is the best way to handle the case where the string is greater than the limit of SIZE_MAX_LINE?

void TextFileReader::read(string inFilename) { ifstream xInFile(inFilename.c_str()); if(!xInFile){ return; } char acLine[SIZE_MAX_LINE + 1]; while(xInFile){ xInFile.getline(acLine, SIZE_MAX_LINE); if(xInFile){ m_sStream.append(acLine); //Appending read line to string } } xInFile.close(); } 
+6
c ++
source share
3 answers

Do not use istream::getline() . It deals with bare character buffers and is therefore error prone. It is better to use std::getline(std::istream&,std::string&, char='\n') from the <string> header:

 std::string line; while(std::getline(xInFile, line)) { m_sStream.append(line); m_sStream.append('\n'); // getline() consumes '\n' } 
+10
source share

Since you are already using C ++ and iostream, why not use the std::string getline function ?

 std::string acLine; while(xInFile){ std::getline(xInFile, acLine); // etc. } 

And use xInFile.good() to ensure that eofbit and badbit and failbit not installed.

+9
source share

If you use a free function in a line, you do not need to skip the maximum length. It also uses the C ++ string type.

+2
source share

All Articles