- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的代码:
#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/
我在使用以下模板函数时遇到问题。 /// Remove leading and trailing space and tab characters from a string. /// @param[
据我所知,noskipws 禁止跳过空格。因此,如果他们想使用 noskipws,就需要在他们的程序中使用一些字符来占用空白。我尝试通过按 Ctrl+D 将 cin 设置为 eof 条件(Ctrl+Z
我的方法是否正确读取包含空格和换行符 (\n) 的 .txt 文件?我编写程序的说明还要求我检测空格和换行符,以便可以对它们进行操作。 char word_from_file; ifstream in
我希望能够输入完整的字符串(包括空格),然后打印该字符串。 为什么此代码不符合我的预期? 代码 #include #include using namespace std; int main()
这是我的代码: #include #include using namespace std; int main(){ int x=-1; while(x != 0) {
为了设置std::skipws(或std::noskipws)标志,需要这样写: my_input_stream >> std::skipws; //or my_input_stream >> std
我正在学习 C++。 我正在尝试转换这样的文本文件: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
最初问 here . 如果我使用以下代码将“Hello world”发送到 cin... string str,msg; getline(cin,str); stringstream ss(str);
首先我的理解是 cin >> std::noskipws >> str; 应该将 cin 中的整行(例如“我有空格”)粘贴到 str 中。然而,这只会将“i”放入 str。这可能是一个错误的假设,在这
我遇到了 Reading the binary file into the vector of unsigned chars并测试了问题中讨论的代码。 感兴趣的代码如下: typedef unsign
我是一名优秀的程序员,十分优秀!