gpt4 book ai didi

c++: noskipws 延迟了某些数据类型的文件结束检测

转载 作者:可可西里 更新时间:2023-11-01 16:48:34 26 4
gpt4 key购买 nike

据我所知,noskipws 禁止跳过空格。因此,如果他们想使用 noskipws,就需要在他们的程序中使用一些字符来占用空白。我尝试通过按 Ctrl+Dcin 设置为 eof 条件(Ctrl+Z 适用于 Windows)。但是,如果我使用 charstring 输入,则流将设置为具有单个输入的文件结尾。但是,如果我使用其他数据类型,则需要我按组合键两次。如果我删除 noskipws 请求,其他一切正常。下面的代码更准确地解释了这个问题:

#include <iostream> 

using namespace std;

int main()
{
cin >> noskipws; //noskipws request
int number; //If this int is replaced with char then it works fine
while (!cin.bad()) {
cout << "Enter ctrl + D (ctrl + Z for windows) to set cin stream to end of file " << endl;
cin >> number;
if (cin.eof()) {
break; // Reached end of file
}
}
cout << "End of file encountered" << endl;

return 0;
}

为什么 cin 会这样?虽然它不能将输入放入 int 变量,但它至少应该在收到请求时立即将标志设置为 eof。为什么即使在用户按下 Ctrl+Z 后它仍需要第二次输入?

最佳答案

当使用noskipws 时,您的代码负责提取空格。当您读取 int 时,由于遇到空白,它会失败。

参见 an example :

#include <iostream>
#include <iomanip>
#include <cctype>

#define NOSKIPWS

#define InputStreamFlag(x) cout << setw(14) << "cin." #x "() = " << boolalpha << cin.x() << '\n'

using namespace std;

int main()
{
#ifdef NOSKIPWS
cin >> noskipws;
char ch;
#endif
int x;
while (cin >> x) {
cout << x << ' ';
#ifdef NOSKIPWS
while (isspace(cin.peek()))
{
cin >> ch;
}
#endif
}
cout << endl;

InputStreamFlag(eof);
InputStreamFlag(fail);
InputStreamFlag(bad);
InputStreamFlag(good) << endl;

return 0;
}

visual studio .

关于c++: noskipws 延迟了某些数据类型的文件结束检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37784797/

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