我有一个从终端获取输入的C ++程序,由于某种原因,这会产生无限循环:
double getSideLength()
{
cout << "Enter a side: "
double side;
cin >> side; cin.ignore( 80, '\n' );
while (side <= 0){
cout << "Please enter a valid side. Try again: ";
cin >> side; cin.ignore(80, '\n');
}
return side;
这会产生输出:
Enter a side: invalid
Please enter a valid side. Try again:
Please enter a valid side. Try again:
Please enter a valid side. Try again:
.... and so on. "invalid" is the only input the user made
答案 0 :(得分:2)
如operator>> documentation流中所述,如果“获得的输入不能被解释为适当类型的元素”,则获取其failbit。如果您输入错误的号码,就会发生所以你必须在下一次输入之前清除()cin。这是代码:
double getSideLength()
{
double side;
cout << "Enter a side: ";
cin >> side;
if (!cin)
cin.clear();
cin.ignore( 80, '\n' );
while (side <= 0){
cout << "Please enter a valid side. Try again: ";
cin >> side;
if (!cin)
cin.clear();
cin.ignore( 80, '\n' );
}
return side;
}
答案 1 :(得分:1)
这应解决问题。使用!(cin >> side)
将确保我们从cin获得正确的类型。
double getSideLength()
{
cout << "Enter a side: " << std::endl;
double side = -1;
while ( ! (cin >> side) and side <= 0)
{
cout << "Please enter a valid side. Try again: ";
cin.clear();
cin.ignore(1000, '\n');
}
return side;
}
答案 2 :(得分:0)
double getSideLength()
{
double side;
getinput:
cout << "Enter a side: "
cin >> side; cin.ignore( 80, '\n' );
if(side <= 0)
{
cout << "Please enter a valid side. Try again: "
goto getinput;
}
return side;
}
尝试这个我希望这对你有帮助
答案 3 :(得分:0)