这是我的代码:
#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;
它消耗所有字符,直到找到非空白字符。
关于c++ - 为什么 `cin >> noskipws` 不等待输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47875065/