gpt4 book ai didi

c++ - 从 ifstream 读取时出现多余的空行

转载 作者:行者123 更新时间:2023-11-28 03:57:07 24 4
gpt4 key购买 nike

在我的程序中,我已重定向标准输出以打印到文件“console.txt”。一个函数像这样写入该文件:

void printToConsole(const std::string& text, const TCODColor& fc, const TCODColor& bc)
{
// write the string
cout << text << "@";

// write the two color values
cout << static_cast<int>(fc.r) << " "
<< static_cast<int>(fc.g) << " "
<< static_cast<int>(fc.b) << " "
<< static_cast<int>(bc.r) << " "
<< static_cast<int>(bc.g) << " "
<< static_cast<int>(bc.b) << " " << endl;
}

我有一个从该文件中读取的函数,如下所示:

   void Console::readLogFile()
{
ifstream log("console.txt", ifstream::in);
if(!log.is_open())
{
cerr << "ERROR: console.txt not found!" << endl;
return;
}

// read new input into the stack
char str[256];
while(!log.eof())
{
log.getline(str, 256);
cerr << "str: " << str << endl;
stk.push(static_cast<string>(str));
// stk is a std::stack<std::string> member of the class this function
// belongs to.
}
cerr << endl;

/* Do some stuff with str and stk here */

log.close();
clearLogFile();
}

void Console::clearLogFile()
{
FILE* log;
log = fopen("console.txt", "w");
fclose(log);
}

调用 readLogFile 时,console.txt 通常为空。我希望 while(!log.eof()) 循环在那种情况下永远不会执行,但它会执行。文件中总是至少有一个多余的空行,有时有两个,当从文件中读取输入时,输入行夹在两个空行之间。调用此函数几次后,while(!log.eof()) 循环进入无限循环,从文件中提取空行。该程序的典型运行过程如下所示:

str: 

str: Player moved.@191 191 191 0 0 0
str:

str:
str: Player moved.@191 191 191 0 0 0
str:

str: // there should be a 'Player moved.' line in here
str:

str: // here as well
str:

str: // also here
str:

str:
str: Player moved.@191 191 191 0 0 0
str:

str:
str:
str:
str:
str:
str:
(onto infinite loop)

谁能看出我在这里做错了什么?

编辑:正如 Amardeep 所建议的,我将 while(!log.eof()) 循环更改为 do{...}while(!log.fail);循环。这解决了无限循环问题,但没有解决多余的行。该程序的行为与以前一样,除了它曾经进入无限循环的地方,它现在只读取它应该读取输入的空白​​行,如下所示:

str:

str:

str:

str:
(etc.)

最佳答案

eof() 状态在您尝试读取之前不会设置。您应该更改读取循环以执行 getline() 然后检查 fail() 状态,而不是依赖 eof(),这不涵盖尝试读取文件时可能出错的范围。

关于c++ - 从 ifstream 读取时出现多余的空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3113055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com