为什么 `cin >> noskipws` 不等待输入?

Why `cin >> noskipws` doesn't wait for input?

这是我的代码:

#include <iostream>
#include <vector>

using namespace std;

int main(){
    int x=-1;
    while(x != 0)
    {
        x = 0;

        cout << "nuevo numero: ";
        cin >> noskipws >> x;
        cout << x << endl;;
    }
}

输出为:

nuevo numero: 5  // I input that number
5
nuevo numero:    // Here it doesn't wait for an input
0                // I don't know where this come from, guess it's the empty input

我知道这与 noskipws 有关,但我不知道确切原因,也不知道如何解决。

问题: 为什么第二个 cin >> noskipws 不等待输入?我该如何解决?

Why the second cin >> noskipws doesn't wait for input?

因为不需要请求输入:你的程序还没有处理它已经给出的输入。

当您输入第一个数字时,您按了5,然后输入。它向输入流中插入两个字符:'5''\n'。第一个输入操作读取 '5',它是一个可以接受的字符,所以它会消耗它。然后它看到'\n',它不是数字中的有效字符,所以它停在那里,在流中留下'\n'并从已经读取的内容构造数字。

在下一个输入操作中,它会在输入流中看到 '\n'。它不是数字的有效字符,因此它会立即停止。通常,在尝试输入操作之前会跳过空白字符(这会导致输入缓冲区耗尽并请求更多输入),但您明确要求不要这样做(通过设置 noskipws 标志)。所以,你得到了你想要的。

如果你想模仿流在空格跳过方面的默认行为,但不想禁用 noskipws 标志,你可以使用 std::ws 操纵器:

std::cin >> std::ws >> i;

它消耗所有字符,直到找到非空白字符。

If you use noskipws, then the first step is skipped. After the first read, you are positionned on a whitespace, so the next (and all following) reads will stop immediatly, extracting nothing.

您的程序未能执行的操作是检查从流中提取号码是否成功。

更新要使用的程序:

    cout << "nuevo numero: ";
    if ( cin >> noskipws >> x )
    {
       cout << x << endl;;
    }
    else
    {
       cout << "Unable to read.\n";
    }

您会注意到第二次调用失败了。失败是因为您指定了 noskipws 但流中没有任何内容可以提取整数。

noskipws 操纵器适用于从流中读取字符,但不适用于读取数字。