[英]How do I read long lines from a text file in 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?
处理行大于限制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();
}
Don't use istream::getline()
. 不要使用
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: 最好从
<string>
标头使用std::getline(std::istream&,std::string&, char='\\n')
:
std::string line;
while(std::getline(xInFile, line)) {
m_sStream.append(line);
m_sStream.append('\n'); // getline() consumes '\n'
}
Since you're using C++ and iostream already, why not use std::string
's getline
function ? 既然你已经在使用C ++和iostream了,为什么不使用
std::string
的getline
函数呢?
std::string acLine;
while(xInFile){
std::getline(xInFile, acLine);
// etc.
}
And, use xInFile.good()
to ensure eofbit
and badbit
and failbit
are not set. 并且,使用
xInFile.good()
来确保未设置eofbit
和badbit
以及failbit
。
If you use the free function in string, you don't have to pass a max length. 如果在字符串中使用自由函数 ,则不必传递最大长度。 It also the uses C++ string type.
它还使用C ++字符串类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.