Home  >  Q&A  >  body text

C/C++如何判断用户输入是否合法?

int a;
scanf("%d",&a);
cin>>a;

ex:我想让用户输入整数,但是如果用户输入的不是我想要的类型如!%$#,abcd....都有什么方法或者函数去判断呢?

大家讲道理大家讲道理2764 days ago531

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 11:36:21

    The return value of

    scanf is the number of normal reads, so just judge the return value.

    if(scanf("%d", &a) == 1) 
        printf("OK!");
    else
        printf("Failed to read an integer.");
    

    But a big pitfall of scanf is that it will stop scanning when it encounters invalid characters and leave invalid characters in the buffer, so it will always detect failures and enter an infinite loop. If you encounter this problem, you can use the following solutions to solve it:

    int a;
    while(1 != scanf("%d", &a)) {
        fflush(stdin);    // 刷新缓冲区
        cout << "Invalid input! Please check and input again: ";
    }
    cout << "a = " << a << endl;
    cout << "Test finished!";
    return 0;
    

    Of course, this is not a good choice. It is best to avoid using scanf in this situation. You can read the string first, then check the string validity, and use some library functions (such as sscanf, isdigit, atoi, etc.) to convert a string into an integer.

    reply
    0
  • PHPz

    PHPz2017-04-17 11:36:21

    I remember doing similar questions in my freshman year, and they were all judged using regular expressions.

    string str;
    cin >> str;
    const regex re("\d+");
    if(!regex_match(str, re))
      //....
    else
      int num = stoi(str);
    

    reply
    0
  • Cancelreply