我正在学习C++,所以我不太了解这里的代码是怎么回事,但是从我能够搜集到的信息来看,这似乎可能是某种缓冲区问题。
#include <stdio.h>
#include <vector>
#include <iostream>
#include <typeinfo>
using namespace std;
bool stopRun = true;
int height, average, total, count;
vector <int> heights;
int main ()
{
while (stopRun)
{
cout << "Enter a height, or 'end' to quit: ";
cin >> height;
if (typeid(height).name() == "i")
{
heights.push_back(height);
cout << heights[0];
count++;
}
else if (typeid(height).name() == "i")
{
cout << "\nPlease enter an integer: ";
continue;
}
if (count == 5)
{
stopRun = false;
}
}
for (int i = 0; i < heights.size(); i++)
{
total += heights[i];
cout << "\nTotal: " << total;
}
return 0;
}
由于某些原因,此代码将连续输出:“输入高度,或'结束'以退出:”。在较早的版本中,它将输出:“输入高度,或'结束'以退出:请输入整数:”。
我认为这是我的“高度>>高度”;行从“请输入整数:”中提取输出,并将其作为我的输入,这将其标识为不是整数类型,这将启动无限循环。
如何清除输入缓冲区,以免输入cout语句?还是我在这里遇到的问题?
提前致谢!
最佳答案
我建议抓紧绳子。如果字符串不是“end”,则在try / catch中转换为数字
关于c++ - C++中的cin缓冲区问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61181517/