【发布时间】:2012-10-24 02:30:27
【问题描述】:
我对应该非常简单的代码有疑问。我想通过错误检查获取 1 到 3 之间的整数。它适用于检查太大或太小的数字,但是当输入字母/数字组合时,它会陷入无限循环。有什么建议吗?
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
int input;
cout << "\nPlease enter a number from 1 to 3:" << endl;
cout << "-> ";
cin >> input;
while(input< 1 || input> 3){
cout << "\n---------------------------------------" << endl;
cout << "\n[!] The number you entered was invalid." << endl;
cout << "\nPlease re-enter a number from 1 to 3" << endl;
cout << "-> ";
cin >> input;
}
cout << "You chose " << input << endl;
}
【问题讨论】:
标签: c++ error-handling integer infinite-loop