C++如何使用GETLIN()检测EOF

C++如何使用GETLIN()检测EOF,c++,C++,这个问题有一些变体,但没有一个完全符合我的要求 给出以下代码: string command=""; while (command.compare("quit")!=0) { os << prompt; getline(is,command); } 如何检测getline是否达到文件末尾的eof while (command.compare("quit")!=0) { os << pr

这个问题有一些变体,但没有一个完全符合我的要求

给出以下代码:

string command="";

while (command.compare("quit")!=0)
{
    os << prompt;
    getline(is,command);
}
如何检测getline是否达到文件末尾的eof

while (command.compare("quit")!=0)
{
    os << prompt;
    getline(is,command);
    if (is.eof())
         do something at end of file
}
如果到达文件末尾且未输入任何内容,或者输入了“quit”,则该代码将退出循环。

getline返回对传递给它的流的引用,如果该流达到故障状态,则该流将计算为false。知道了这一点,您可以利用它将getline移动到while循环的条件中,这样如果它失败,那么条件将为false,循环将停止。您可以将这两个选项组合在一起,以检查是否退出

while (getline(is,command) && command != "quit")
{
    // stuff
}
您还可以将提示添加到循环中,如

while (os << prompt && getline(is,command) && command != "quit")

您应该避免在循环中使用eof的尝试,因为这样做:看起来更像是flagsbetter,只需检查is==false@drescherjm什么意思?我想在到达文件末尾时退出循环,以便与操作代码兼容:while os@bruno这是个好主意。我使用了&&而不是,只是为了保持一致性。如何将getline返回的内容保存在变量中,以便将其传递给另一个函数?@daniel getline returns是这样的it@danielgetline总是返回对传递给它的流的引用,在本例中是。os我的意思是什么是变量类型int string等?
while (os << prompt && getline(is,command) && command != "quit")