[求助]如何验证变量输入是否合法
比如一个int型变量用户输入'q'怎么检测到非法并让用户重新输入呢?
你是怎么获得int的呢?如果是scanf,看其返回值,istream类似。
知道不对后,再将不对的字符读出来扔掉。
看代码吧,没代码只能瞎鸡巴胡说
程序代码:#include <iostream>
#include <limits>
using namespace std;
int main( void )
{
const int result = -123;
for( size_t n=1; n!=4; ++n )
{
int answer;
if( cin>>answer )
{
if( answer == result )
{
cout << "…………" << endl;
break;
}
}
else
{
cin.clear();
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
}
if( n < 3 )
cout << "…………:";
}
return 0;
}