【发布时间】:2012-08-10 01:19:01
【问题描述】:
我正在尝试使用 getline 读取一串文本。出于某种原因,它会打印两次“请输入您的选择”:
Please enter your selection
Please enter your selection
如果我键入无效文本,它会再次循环,之后每次循环只打印一次。
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.
}
有人知道为什么会发生这种情况吗?
谢谢
【问题讨论】:
-
在第一次打印后尝试刷新 std::cout:flush(cout);
-
@Ben,
endl应该为交互式设备自动执行此操作。 -
你能给我们一些(简短的)可编译代码来重现问题吗?
-
您可以在循环之前尝试
cin.ignore(INT_MAX); cin.clear();吗? -
@scientiaesthete,这不会一直读到 EOF 吗?这是我的理解,虽然我可能错了。
标签: c++