我正在从我的网络摄像头捕获视频,如果用户点击Enter键,我会拍照。然后我问“图片好吗?”用户并等待输入。如果他说“不”,我会继续做同样的事情,直到他说“是”。
但如果他说“不”,同时我在终端输入内容,getline()函数会将我输入的内容写入其缓冲区,当我再次询问问题时,它会直接转到“无效输入”状态
如何防止这种情况?
我已经阅读了很多关于此问题的问题,我在调用getline()之后尝试使用cin.ignore()和cin.clear(),但是他们没有帮助。
// Do capturing here
string choice;
int choiceIsOkay = 0;
while (choiceIsOkay == 0)
{
cout << "Is the picture okay? (Y/N): ";
getline(cin, choice);
if ((choice == "Y") || (choice == "y"))
{
choiceIsOkay = 2;
}
else if ((choice == "N") || (choice == "n"))
{
choiceIsOkay = 1;
}
else
{
cout << "\nInvalid input\n";
choiceIsOkay = 0;
}
}
if (choiceIsOkay == 2)
{
runAlgorithm = 1;
break;
}
else choiceIsOkay = 0;
答案 0 :(得分:0)
如果我了解您的问题,如果用户输入Some Random Text In
,您的程序将始终跳入&#34;输入无效&#34;并且永远不会停止等待用户输入。以下代码可以解决您的问题。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int runAlgorithm;
// Do capturing here
int i = 0;
while (i++ < 3)
{
int choiceIsOkay = 0;
string choice;
while (choiceIsOkay == 0)
{
cout << "Is the picture okay? (Y/N): ";
getline(cin, choice);
if ((choice == "Y") || (choice == "y"))
{
choiceIsOkay = 2;
}
else if ((choice == "N") || (choice == "n"))
{
choiceIsOkay = 1;
}
else
{
cout << "nInvalid inputn";
choiceIsOkay = 0;
}
// Ignore to the end of line
cin.clear();
}
}
return 0;
}