问题描述
我正在尝试使用getline读取一串文本.由于某种原因,它会两次打印请输入您的选择":
I'm trying to read in a string of text using getline. For some reason, it prints 'Please enter your selection' twice:
Please enter your selection
Please enter your selection
如果我键入无效的文本,它将再次循环播放,此后每次循环仅打印一次.
If I key invalid text, it loops again, and only prints the one time each loop thereafter.
while (valid == false) {
cout << "Please enter your selection" << endl;
getline (cin,selection);
// I have a function here which checks if the string is valid and sets it to true
// if it is valid. This function works fine, so I have not included it here. The while
// look breaks correctly if the user enters valid input.
}
有人知道为什么会发生这种情况吗?
Does anybody have any idea why this may be occurring?
谢谢
推荐答案
可能进入循环时,上一次操作的输入缓冲区中仍然存在某些东西.
Probably there's something still in the input buffer from a previous operation when you enter the loop.
它被 getline
拾取,发现无效,然后循环再次运行.
It's picked up by the getline
, found to be invalid, then the loop runs again.
通过示例,假设进入循环之前,您读取了一个字符.但是,在熟模式下,需要先输入字符和换行符,然后才能执行该操作.
By way of example, let's say that, before you enter the loop, you read a single character. But, in cooked mode, you'll need to enter the character and a newline before it's actioned.
因此,您读取了字符并将换行符保留在输入缓冲区中.
So, you read the character and the newline is left in the input buffer.
然后,您的循环开始,读取换行符,并认为它无效,然后循环返回以获取 actual 输入行.
Then your loop starts, reads the newline, and deems it invalid so it then loops back to get your actual input line.
当然,这是一种可能性,当然还有其他可能性-它很大程度上取决于循环之前的代码 以及它对 cin
的作用.
That's one possibility though, of course, there may be others - it depends very much on the code before that loop and what it does with cin
.
如果是 情况,则类似:
cin.ignore(INT_MAX, '\n');
在循环可能修复它之前.
before the loop may fix it.
或者,您可能要确保在所有地方都使用基于行的输入.
Alternatively, you may want to ensure that you're using line-based input everywhere.
这里有一些代码可以看到这种情况的发生:
Here's some code to see that scenario in action:
#include <iostream>
#include <climits>
int main(void) {
char c;
std::string s;
std::cout << "Prompt 1: ";
std::cin.get (c);
std::cout << "char [" << c << "]\n";
// std::cin.ignore (INT_MAX, '\n')
std::cout << "Prompt 2: ";
getline (std::cin, s);
std::cout << "str1 [" << s << "]\n";
std::cout << "Prompt 3: ";
getline (std::cin, s);
std::cout << "str2 [" << s << "]\n";
return 0;
}
附有笔录:
Prompt 1: Hello
char [H]
Prompt 2: str1 [ello]
Prompt 3: from Pax
str2 [from Pax]
,您可以看到它实际上并没有等待提示2的新输入,它只是获得了您在提示1输入的其余行,因为字符,,,和仍在输入缓冲区中.
in which you can see that it doesn't actually wait around for new input for prompt 2, it just gets the rest of the line you entered at prompt 1, because the characters , , , and are still in the input buffer.
取消注释 ignore
行时,它会以您期望的方式运行:
When you uncomment the ignore
line, it acts in the manner you'd expect:
Prompt 1: Hello
char [H]
Prompt 2: from Pax
str1 [from Pax]
Prompt 3: Goodbye
str2 [Goodbye]
这篇关于为什么当我使用getline时cout打印两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!