如何使用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;
}
你錯過了幾這段代碼中的變量聲明。 – WhozCraig 2013-04-20 05:57:00
http://www.parashift.com/c++-faq/istream-and-ignore.html – chris 2013-04-20 06:00:34
大多數情況下,在C++中,您的讀取語句需要處於while循環的條件。那麼失敗將導致while循環終止而不是你的程序。 – 7stud 2013-04-20 06:11:46