3 回答
TA貢獻2003條經驗 獲得超2個贊
您可以像這樣檢查:
int x;
cin >> x;
if (cin.fail()) {
//Not an int.
}
此外,您可以繼續獲取輸入,直到通過以下方式獲取整數為止:
#include <iostream>
int main() {
int x;
std::cin >> x;
while(std::cin.fail()) {
std::cout << "Error" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> x;
}
std::cout << x << std::endl;
return 0;
}
編輯:要解決以下有關10abc之類的輸入的注釋,可以修改循環以接受字符串作為輸入。然后檢查字符串中是否包含數字以外的任何字符,并相應地處理該情況。在那種情況下,不需要清除/忽略輸入流。驗證字符串只是數字,然后將字符串轉換回整數。我的意思是,這只是袖手旁觀。可能有更好的方法。如果您接受浮點數/雙精度數,則此方法將無效(必須在搜索字符串中添加“?!保?/p>
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin, theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
- 3 回答
- 0 關注
- 603 瀏覽
添加回答
舉報
