注册 登录
编程论坛 C++教室

[求助]如何验证变量输入是否合法

家力掠 发布于 2015-12-13 13:51, 1909 次点击
比如一个int型变量用户输入'q'怎么检测到非法并让用户重新输入呢?
5 回复
#2
rjsp2015-12-13 18:54
你是怎么获得int的呢?如果是scanf,看其返回值,istream类似。
知道不对后,再将不对的字符读出来扔掉。

看代码吧,没代码只能瞎鸡巴胡说
#3
家力掠2015-12-13 22:07
回复 2楼 rjsp
程序代码:
for(n = 1; n < 4; n++)

 49       {

 50          cin>>answer;

 51          if(answer == result)

 52          {

 53             cout<<"回答正确"<<endl;

 54             break;

 55          }

 56          else if(n < 3)

 57             cout<<"回答错误.请重新输入:";

 58       }

相关部分代码是这样的.如果我输入一个'q'后就直接循环结束了.
我想问下怎么才能检测到输入不正确后让用户重新输入.
#4
rjsp2015-12-14 08:44
程序代码:
#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;
}
#5
yzyou5212016-01-07 11:02
新手一枚  有个笨办法  那就是再次回显让用户确认  代码如下:
程序代码:
char ans;
do
{
    cin>>num;
    cout<<"You input a numer:"<<num<<endl;
    cout<<"Is it correct?"<<endl;
    cin>>ans;
}while(ans!='y'||ans!='Y');    //输入y||Y确认,否则重新输入


[此贴子已经被作者于2016-1-7 11:03编辑过]

#6
yangfrancis2016-01-07 12:06
char num_str[10];
do
{
    bool invalid=false;
    cin>>num_str;
    short len=strlen(num_str);
    for(short i=0;i<len;i++)
        if(num_str[i]<'0'||num_str[i]>'9')
        {     
             invalid=true;
             cout<<"非法输入!";break;
        }
 }while(invalid);
//尚未测试
1