我有一个任务,我必须制作一个程序,该程序接受用户输入(需要自然数),然后打印出反向数字。该程序做得很好但是我还必须确保在输入不是自然数的值时程序不会给我任何错误。如果我输入双精度值或输入数字后跟字符,程序将退出。在其余情况下,该程序运行良好。什么可能导致这些问题?
int number;
char x = 'c';
while (x == 'c') {
cout << "Enter a number\n";
cin >> number;
while (!(cin.good()) || number < 1 || floor(number) != number) {
cin.clear();
cin.ignore(256,'\n');
cout << "Try again.\n";
cin >> number;
}
string reverse;
stringstream convert;
convert << number;
reverse = convert.str();
reverse = string (reverse.rbegin(),reverse.rend());
cout << "The reverse number for number " << number << " is " << reverse << endl;
cout << "If you want to continue using the program enter 'c',\nif you want to close the program enter anythin else\n";
cin >> x;
}