2015-10-20 36 views
0

我的代碼是:循環的立即退出時輸入不是C中的無符號++

unsigned numbers, x = 0, odds = 0; 
cout << "Input numbers to find the amount of odds. " << endl; 
while (x < 9999){ 
    cin >> numbers || die("Input Error"); 
    if (numbers % 2 == 1) { 
     odds++; 
    } 
} 
cout << "There are " << odds << " odds." << endl; 

return 0; 

我怎麼能放棄當用戶輸入對數字的非數字值的循環?先進的謝謝你。

+1

[讀「無符號整數」使用「CIN」]的可能的複製(http://stackoverflow.com/questions/9574771/reading-unsigned-int-using-cin) – Downvoter

回答

1

您可以使輸入成爲循環的條件。

while (cin >> numbers) 
{ 
    //... 
} 

將運行,直到用戶輸入的東西不能輸入到numbers。如果你想有檢查numbers < 9999還有那麼我們將不得不

while (std::cin >> numbers && numbers < 9999) 
{ 
    //... 
} 
+0

這是不正確的。見:https://stackoverflow.com/questions/7465494/how-to-compare-an-ascii-value – Nandu

+0

@Nandu什麼?這與此無關,它是錯誤的語言。 – NathanOliver

+0

您的解決方案不適用於'123a' – Nandu

0
#include <cctype> 
std::string str; 
cin >> str; 
for (std::string::iterator it=str.begin(); it!=str.end(); ++it) 
if (!std::isdigit(*it)) { 
    cout << "non-digit"); 
    return; 
} 
0

你正在尋找的關鍵詞是break

while (x < 9999) { 
    if((cin >> numbers).fail()) 
     break; 

    if (numbers % 2 == 1) { 
     odds++; 
    } 
} 
+0

不正確。見:https://stackoverflow.com/questions/7465494/how-to-compare-an-ascii-value – Nandu

+0

@南都可以請你詳細說明,爲什麼你認爲,這是不正確的?你的鏈接與問題和我的回答完全無關。 – cdonat

-1

使用hash_fun評估字符串和ingnore任何非數值

+4

什麼是「hash_fun」以及如何使用它?請改善你的答案。 –