C++ 如何从C++;?
我使用以下代码从文本文件中读取行。处理线大于极限尺寸\u MAX\u线的情况的最佳方法是什么C++ 如何从C++;?,c++,C++,我使用以下代码从文本文件中读取行。处理线大于极限尺寸\u MAX\u线的情况的最佳方法是什么 void TextFileReader::read(string inFilename) { ifstream xInFile(inFilename.c_str()); if(!xInFile){ return; } char acLine[SIZE_MAX_LINE + 1]; while(xInFile){ xInFile.
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();
}
如果使用in字符串,则不必传递最大长度。它也使用C++字符串类型。因为你已经使用C++和iOFFROW,为什么不使用<代码> STD::String < /Cord>?< /P>
使用
xInFile.good()
确保未设置eofbit
和badbit
和failbit
。不要使用istream::getline()
。它处理裸字符缓冲区,因此容易出错。最好使用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'
}
实际上,我想知道如何处理函数设置的eofbit和failbit如果使用std::strings,则不需要测试大小限制,那么一条读取行的大小是多少?读取行的大小是多少
std::string
在运行时根据需要动态扩展。我只需执行“while(std::getline(xInFile,acLine)){}”Kenny,当输入失败时,这将尝试处理//等部分中的旧数据。(如果字符串是函数的本地字符串,那么它至少是一个空字符串。)最好使用Nikko的习惯用法。看,这个怎么样?istream_迭代器游标(xInFile);istream_迭代器端点标记;当(cursor!=endmarker){m_sStream.append(*cursor);cursor++}@sonofdelphi:IIUC时,它将读取单词,而不是行(其中“单词”是由空格分隔的任何内容)。为了让它读取行,您必须使用读取行而不是单词的类型实例化std::istream\u迭代器
。想出这样一个类型应该不难,但是std库中没有。
std::string line;
while(std::getline(xInFile, line)) {
m_sStream.append(line);
m_sStream.append('\n'); // getline() consumes '\n'
}