// Validation and entry for ticket price
void ValidateTicketPrice ( double &ticket_price ){
string error_string;
cin >> ticket_price;
while(1)
{
if(cin.fail())
{
cin.clear();
getline ( cin, error_string);
cout << error_string << " is not a valid ticket price. Please re-enter the data: ";
cin >> ticket_price;
} else {
Flush();
break;
}
}
}
答案 0 :(得分:0)
试试这个:
一直读完整行。然后尝试将该行转换为字符串。如果它转换,返回。否则再试一次。
void ValidateTicketPrice ( double &ticket_price ){
std::string input;
while(std::getline (std::cin, input))
{
char * endp;
ticket_price = strtod(input.c_str(), &endp);
if (*endp == '\0')
{ // number conversion and input ended at same place. Whole input consumed.
return;
}
else
{ // number and strign did not end at the same place. bad input.
std::cout << input << " is not a valid ticket price. Please re-enter the data: ";
}
}
}