2013-04-20 43 views
0

如何使用C++檢查非數字輸入?我正在使用cin讀取float值,並且我想檢查是否通過stdin輸入非數字輸入。我試圖用%d指示符來使用scanf,但我的輸出已損壞。當使用cin時,我得到正確的格式,但是當輸入字符串如「dsffsw」時,我得到一個無限循環。 評論的代碼是我試圖捕獲浮動,並將其轉換爲字符串,並檢查它是否是一個有效的浮動,但檢查總是出現錯誤。檢查C++程序中的非數字輸入

我嘗試過使用其他方法在留言板上找到,但他們想在C中使用scanf而不是在C++中使用cin。你如何在C++中做到這一點?或者在C中如果不可行。

while (!flag) { 
     cout << "Enter amount:" << endl; 
     cin >> amount; 


    cout << "BEGIN The amount you entered is: " << strtod(&end,&pend) << endl; 

     //if (!strtod(((const char *)&amount), NULL)) { 
     // cout << "This is not a float!" << endl; 
     // cout << "i = " << strtod(((const char *)&amount), NULL) << endl; 
     // //amount = 0.0; 
     //} 

     change = (int) ceil(amount * 100); 

     cout << "change = " << change << endl; 

     cout << "100s= " << change/100 << endl; 
     change %= 100; 
     cout << "25s= " << change/25 << endl; 
     change %= 25; 
     cout << "10s= " << change/10 << endl; 
     change %= 10; 
     cout << "5s= " << change/5 << endl; 
     change %= 5; 
     cout << "1s= " << change << endl; 
     cout << "END The amount you entered is: " << amount << endl; 
} 
return 0; 

}

+0

你錯過了幾這段代碼中的變量聲明。 – WhozCraig 2013-04-20 05:57:00

+0

http://www.parashift.com/c++-faq/istream-and-ignore.html – chris 2013-04-20 06:00:34

+0

大多數情況下,在C++中,您的讀取語句需要處於while循環的條件。那麼失敗將導致while循環終止而不是你的程序。 – 7stud 2013-04-20 06:11:46

回答

1
int amount; 

cout << "Enter amount:" << endl; 

while(!(cin >> amount)) { 
    string garbage; 
    cin.clear(); 
    getline(cin,garbage); 
    cout << "Invalid amount. " 
     << "Enter Numeric value for amount:" << endl; 
} 
+0

我喜歡'getline(cin,garbage)',它比cin.ignore(std :: numeric_limits :: max(),'\ n')'更加明顯。但是垃圾的聲明應該在while循環中移動。 – john 2013-04-20 06:16:58

+0

@john你好點。將解決。 – stardust 2013-04-20 06:17:56

0

試試這個方法來檢查的有效性:

float amount; 

if (cin >> amount) 
{ 
    cout << "Ok" << endl; 
} 
else 
{ 
    cout << "Invalid" << endl; 
} 
0

我想,你的任務涉及所謂防禦式編程,它單曲的想法之一是爲了防止你描述的情況(功能需要一種類型,用戶輸入另一種類型)。

我給你來判斷使用方法,返回流狀態,這是good()
所以我認爲這將是這個樣子的輸入是否正確:

int amount = 0; 
while (cin.good()) { 
     cout << "Enter amount:" << endl; 
     cin >> amount;