2

该程序应检查输入的数字是否为整数。它适用于字符串,但不适用于双打。

 int test;   
  cout << "Enter the number:" << endl;
  while(true) {
    cin >> test;
    if (!cin || test < 0) {
      cout << "Wrong input, enter the number again:" << endl;
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
4

2 回答 2

1

testintistream>> 运算符只是动态转换为 int ,然后,您将丢失小数部分。

你可以定义testfloatint在需要时将其转换为。

编辑:回答你上次编辑(我没有刷新,所以我错过了这部分),发生的事情是,没有goto你循环两次:

  1. 你输入 1.5
  2. test为1且不输入if,所以cin不清理。
  3. 再次循环并cin立即返回。
  4. test为 0,因此进入 if 语句并抱怨。

希望这可以帮助

于 2013-11-14T14:12:06.070 回答
1

尝试这个:

int test;
cout << "Enter the number:" << endl;
while ( true )
{
    cin >> test;
    if (!(test < 0 || !cin))
        break;
}
cout << "Your chosen number is: " << test << endl;

那是你要的吗?

于 2013-11-14T13:56:53.430 回答