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

时间:2016-06-13 08:17:46

标签: c++

根据我对noskipws的了解,它禁止跳过空格。因此,如果他们想要使用noskipws,则需要在程序中使用某些字符来占用空格。我尝试按 Ctrl + D Ctrl + Z)将cin设置为eof条件 for 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 之后又需要第二次输入?

1 个答案:

答案 0 :(得分:0)

使用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