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

Har*_*rma 9 c++

据我所知noskipws,它禁止跳过白色空格.因此,如果他们想要使用,他们需要在他们的程序中使用一些char来获取空格noskipws.我尝试按+ (+ 对于Windows)设置cineof条件.但是如果我使用或输入,则使用单个输入将流设置为文件结尾.但是,如果我使用其他一些数据类型,则需要我按两次组合.如果我删除请求,其他一切正常.以下代码更准确地解释了问题:CtrlDCtrlZcharstringnoskipws

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*k R 0

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

一个例子

#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;
}
Run Code Online (Sandbox Code Playgroud)

或者视觉工作室