这个问题有一些变体,但没有一个与我想要的完全匹配。
给出了以下代码:
string command="";
while (command.compare("quit")!=0)
{
os << prompt;
getline(is,command);
}
如何检测getline
是否达到eof (文件结尾)
发布于 2020-08-04 01:31:28
getline
返回对您传递给它的流的引用,如果流达到失败状态,则该流的计算结果将为false
。了解了这一点后,您可以利用这一点将getline
移到while循环的条件中,以便如果它失败,则条件将为false,并且循环停止。您也可以将其组合到quit
检查中,如下所示
while (getline(is,command) && command != "quit")
{
// stuff
}
您还可以将提示添加到循环中,如下所示
while (os << prompt && getline(is,command) && command != "quit")
发布于 2020-08-04 01:30:38
while (command.compare("quit")!=0)
{
os << prompt;
getline(is,command);
if (is.eof())
do something at end of file
}
但请注意,到达文件末尾并不意味着command
中没有内容。您可以同时读取数据和到达文件末尾。
相反,您可能会查找以下内容
os << prompt;
while (getline(is,command) && command != "quit")
{
do something with command
os << prompt;
}
如果您到达文件末尾,但没有输入任何内容,或者输入了“quit”,则该代码将退出循环。
https://stackoverflow.com/questions/63234211
复制相似问题