做 while 循环..现在:无限,目标:不是无限(问直到循环)
Do while loop.. right now: infinite, goal: not infinite (ask until loop)
所以当我输入一个字符或字符串时,它会无限次地再次询问这个问题......但我希望它每次都问一次错误,如果错误再问一次。得到它... ? :( 现在循环是无限的。
#include <iostream>
using namespace std;
int main() {
float money;
do
{
cout << "How much money do you have? " << endl;
cin >> money;
if (money) {
cout << "You have: " << money << "$" << endl;
} else {
cout << "You have to enter numbers, try again." << endl;
}
} while (!money);
return 0;
}
您没有验证和清除 cin
流的错误状态。试试这个:
#include <iostream>
#include <limits>
using namespace std;
int main() {
float money;
do
{
cout << "How much money do you have? " << endl;
if (cin >> money) {
// a valid float value was entered
// TODO: validate the value further, if needed...
break;
}
else {
// an invalid float was entered
cout << "You have to enter numbers, try again." << endl;
// clear the error flag and discard the bad input...
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
while (true);
cout << "You have: " << money << "$" << endl;
return 0;
}
所以当我输入一个字符或字符串时,它会无限次地再次询问这个问题......但我希望它每次都问一次错误,如果错误再问一次。得到它... ? :( 现在循环是无限的。
#include <iostream>
using namespace std;
int main() {
float money;
do
{
cout << "How much money do you have? " << endl;
cin >> money;
if (money) {
cout << "You have: " << money << "$" << endl;
} else {
cout << "You have to enter numbers, try again." << endl;
}
} while (!money);
return 0;
}
您没有验证和清除 cin
流的错误状态。试试这个:
#include <iostream>
#include <limits>
using namespace std;
int main() {
float money;
do
{
cout << "How much money do you have? " << endl;
if (cin >> money) {
// a valid float value was entered
// TODO: validate the value further, if needed...
break;
}
else {
// an invalid float was entered
cout << "You have to enter numbers, try again." << endl;
// clear the error flag and discard the bad input...
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
while (true);
cout << "You have: " << money << "$" << endl;
return 0;
}