如何从C++中的文本文件中读取长行?

son*_*phi 8 c++

我使用以下代码从文本文件中读取行.处理行大于限制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();
}
Run Code Online (Sandbox Code Playgroud)

sbi*_*sbi 11

不要用istream::getline().它处理裸字符缓冲区,因此容易出错.std::getline(std::istream&,std::string&, char='\n')<string>标题中更好地使用:

std::string line;

while(std::getline(xInFile, line)) {
    m_sStream.append(line);
    m_sStream.append('\n'); // getline() consumes '\n'
}
Run Code Online (Sandbox Code Playgroud)


ken*_*ytm 9

既然你已经在使用C++和iostream了,为什么不使用它std::stringgetline功能呢?

std::string acLine;
while(xInFile){
    std::getline(xInFile, acLine);
    // etc.
}
Run Code Online (Sandbox Code Playgroud)

而且,使用xInFile.good(),以确保eofbitbadbitfailbit没有设置.

  • 我只是做"while(std :: getline(xInFile,acLine)){}" (2认同)