如何从C ++中的文本文件中读取长行? [英] How do I read long lines from a text file in C++?

查看:112
本文介绍了如何从C ++中的文本文件中读取长行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码从文本文件中读取行。

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?

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();
}


推荐答案

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

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'
}

这篇关于如何从C ++中的文本文件中读取长行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆