cin.eof() 的值代表什么C++?

What's the C++ cin.eof()'s value represent?

本文关键字:什么 C++ eof cin      更新时间:2023-10-16
在 istream 中,我使用 cin.getline((

接受一些字符,然后输入 EOF 信号(因为我的操作系统是 MAC,我按 control + D(,然后是第二个 cin.getline(( 来接受流的其余部分。但是,我在第一个cin.getline((之前测试了cin.eof((的值3次,在第一个和第二个cin.getline((之间,最后。在这个程序中,我都使用 EOF 信号来终止这三个 cin.getline((;

代码:

#include<iostream>
using namespace std;
int main()
{
    cout<<"now EOF:"<<cin.eof()<<endl;
    char character[10];
    cout<<"input ten digit character,with '!' in the middle,end with EOF(ctrl+d):"<<endl;
    cin.getline(character, 10,'!');
    cout<<endl;
    cout<<"get the character:"<<endl;
    cout<<character<<endl;
    char character2[10];
    cout<<"now EOF:"<<cin.eof()<<endl;
    cout<<"press(ctrl+d):"<<endl;
    cin.getline(character2, 10,'!');
    //cin>>character2;
    cout<<endl;
    cout<<character2<<endl;
    cout<<"now EOF:"<<cin.eof()<<endl;

}

结果在这里:

now EOF:0
input ten digit character,with '!' in the middle,end with EOF(ctrl+d):
123!456
get the character:
123
now EOF:0
press(ctrl+d):
456
now EOF:1

但是当我用注释的部分 cin>>字符 2 替换 cin.getline(字符 2, 10,'!'( 时:

结果是:

now EOF:0
input ten digit character,with '!' in the middle,end with EOF(ctrl+d):
123!456
get the character:
123
now EOF:0
press(ctrl+d):
456
now EOF:0

我想知道为什么会发生这种情况以及 cin.eof(( 值如何变化。谢谢!

在第二个示例中,换行符仍可供读取 - 您已经读取了一个字符串,而不是一行。

看到输出中缺少的额外换行符了吗?这就是线索。

但更重要的是,不要使用eof。请参阅为什么"while ( !feof (file(("总是错误的?

如果istream::eof()返回true则表示上一个输入操作失败,因为流位于文件末尾。这就是为什么你不能用它来控制输入循环:当它为真时,输入已经失败了。这就是为什么输入操作本身可以告诉你它们是否成功:这样,只要输入成功,你就可以循环。此代码

while (cin.getline(whatever)) {
    do_something(whatever);
}

将在每次getline调用读取一行时执行循环。当cin到达输入末尾时,getline调用将失败,并且不会执行循环。此代码:

while (!cin.eof()) {
    cin.getline(whatever);
    do_something(whatever);
}

将调用do_something,即使对getline的调用失败。调用失败,下次通过循环时,cin.eof()将返回 true,循环将退出。