繁体   English   中英

C++ 如何使用 getline() 检测 eof

[英]C++ how to detect eof using getline()

这个问题有一些变体,但没有一个完全符合我正在寻找的内容。

给出以下代码:

string command="";

while (command.compare("quit")!=0)
{
    os << prompt;
    getline(is,command);
}

我如何检测getline是否达到 eof(文件结尾)

getline返回对您传递给它的 stream 的引用,如果 state 发生故障,则 stream 将评估为false 知道了这一点,您可以利用它来将getline移动到 while 循环的条件中,这样如果它失败,则条件将为 false 并且循环停止。 你可以结合你的检查quit以及像

while (getline(is,command) && command != "quit")
{
    // stuff
}

您还可以将提示添加到循环中,例如

while (os << prompt && getline(is,command) && command != "quit")
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;
}

如果您到达文件末尾并且没有输入任何内容,或者如果输入了“退出”,该代码将退出循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM