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

前端 未结 3 1717
轻奢々
轻奢々 2020-12-19 05:12

I am using the following code for reading lines from a text-file. What is the best method for handling the case where the line is greater than the limit SIZE_MAX_LINE?

相关标签:
3条回答
  • 2020-12-19 05:41

    Don't use istream::getline(). It deals with naked character buffers and is therefor prone to errors. Better 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'
    }
    
    0 讨论(0)
  • 2020-12-19 05:45

    Since you're using C++ and iostream already, why not use std::string's getline function?

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

    And, use xInFile.good() to ensure eofbit and badbit and failbit are not set.

    0 讨论(0)
  • 2020-12-19 06:01

    If you use the free function in string, you don't have to pass a max length. It also the uses C++ string type.

    0 讨论(0)
提交回复
热议问题