gpt4 book ai didi

c++ - cin.clear() 将 EOF 留在流中?

转载 作者:行者123 更新时间:2023-12-05 06:23:00 24 4
gpt4 key购买 nike

我有一个关于cin.clear()的问题,我的cpp代码是这样的:

#include <iostream>

using namespace std;


int main(void)
{
char c, d;
cout << "Enter a char: " << endl;
cin >> c; // here I will enter Ctrl + D (that is EOF under linux)
cin.clear();
cout << "Enter another char: " << endl;
cin >> d;

return 0;
}

我在 2 个系统下编译并运行了这段代码:一个系统是 Debian 7,带有旧版本的软件,如 g++ 和库

 g++ --version
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

另一个系统是 Arch linux,软件版本较新:

g++ --version
g++ (GCC) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

当我运行这个程序时,当它要求我“输入一个字符:”时,我输入 Ctrl + D (EOF)。问题是,当我在 Debian 7 下运行它时,当程序要求我“输入另一个字符:”时,我可以输入一个字符,但我将无法在较新的系统下执行相同的操作,程序刚刚完成。

似乎在旧系统下cin.clear()会清除eof位并刷新流中的EOF,在较新的系统下cin.clear()会清除eof位,但保留流中的 EOF 不变。

这是一些新的cpp标准引起的吗?为什么 cin.clear() 在 2 个系统下表现不同?

最佳答案

我在 Ubuntu 20 中遇到了同样的问题。

我从 How to restart stdin after Ctrl+D? 找到了解决方案

终端并没有真正关闭标准输入流。流仅返回“无”以指示 EOF 或其他问题。

要清除 EOF,在您的程序中调用 clearerr(stdin) 可能会解决问题。

#include <iostream>

using namespace std;

int main(void)
{
char c, d;
cout << "Enter a char: " << endl;
cin >> c;
clearerr(stdin);
cout << "\nEnter another char: " << endl;
cin >> d;

cout << "\n\nc = '" << c << "' and d = '" << d << "'\n\n";

return 0;
}

我的g++版本是9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
我的操作系统是 ubuntu 20 x64
我的终端是 gnome-terminal 3.36.1.1

关于c++ - cin.clear() 将 EOF 留在流中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58732434/

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