2013-11-14 60 views
2

该程序应检查输入的数字是否为整数。它适用于字符串,但不适用于双打。cin in while循环无法正常工作(C++)

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'); 
    } 
+8

你确实是知道的['break'(http://en.cppreference.com/w/cpp/language/break)和['continue']( http://en.cppreference.com/w/cpp/language/continue)声明,不是吗? –

+1

代码工作正常,一切都按照它应该的方式运行,但它没有做你想做的。要做你想做的事情的唯一方法是读取一个*字符串*,检查字符串是否是一个整数格式,然后只将*字符串转换为一个整数。这是很多工作,所以除非你被告知你必须这样做,否则我不会打扰。 – john

+0

不要使用* goto *!作为@JoachimPileborg提到的 –

回答

1

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

哟可以将test定义为float,并在需要时将其转换为int

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

  1. 您输入1.5
  2. test是1,如果你不输入,所以cin没有清理。
  3. 再次循环,cin立即返回。
  4. test是0因此如果语句和抱怨进入。

希望这有助于

0

试试这个:

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

这是你想要的吗?

+0

不,它不是,程序无法正常工作。例如输入“1.2”。休息并没有什么区别,我已经尝试过了。 – user2992251

+0

是否可以使用字符串? – BoBaH6eToH