所以我有一个学校项目需要我等待用户输入 Ctrl + Z 来结束循环。老师说最好的方法是检查 cin >> x
,如果这是真的,那么他们还没有输入 Ctrl + Z。好吧,经过一些测试和来回,我无法弄清楚问题出在哪里,所以我制作了一个 super 简单的代码版本,看看是否可以修复它。什么都没有真正改变。无论如何,这是简单的代码:
#include "Proj_02.h";
vector<int> dog;
string entry = "";
int value = 0;
void main()
{
Menu();
}
void Menu()
{
do
{
//Ask the user to enter a number
cout << "Enter a number: ";
//Save the number to a vector
do
{
cout << "k";
getline(cin, entry);
value = atoi(entry.c_str());
}while(value == 0);
while (cin >> value)
{
cout << "L";
dog.push_back(value);
}
//when the user presses Ctrl + Z stop asking
}while(cin >> entry);
//Display all of the numbers
for(int i = 0;i < dog.size();i++)
{
cout << dog.at(i) << endl;
}
system("PAUSE");
}
所以当它运行时会发生什么是代码等待我再输入 2 个值,然后甚至在完成任何输入之后再做任何事情。我的猜测是它与引起某种缓冲区干扰的 while cin >> entry
有关,但我对如何解决这个问题没有任何可靠的想法。如果有人能提供帮助,那就太好了。
最佳答案
使用流时,请在使用结果之前测试状态。
因此:
while(std::cin >> value) {
...
}
if(std::getline(cin, entry)) {
...
}
关于c++ - 用 while(cin >> x) 填充 std::vector<int> 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18671401/