Maison  >  Questions et réponses  >  le corps du texte

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

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

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

大家讲道理大家讲道理2713 Il y a quelques jours495

répondre à tous(2)je répondrai

  • 大家讲道理

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

    scanf的返回值是正常读取量的数目,所以只要判断返回值即可。

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

    scanf比较大的一个坑是其遇到无效字符会停止扫描并将无效字符留在缓冲区中,所以会一直检测到失败,进入死循环。遇到这种问题,可以使用如下方案解决:

    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;
    

    当然,这也并非一个好的选择,最好是避免在这种情况下使用scanf,可以先按照字符串进行读取,然后检查字符串合法性,使用一些库函数(如sscanfisdigitatoi等等)将字符串转化为整数。

    répondre
    0
  • PHPz

    PHPz2017-04-17 11:36:21

    我记得大一做过类似的题目,当时都是用正则表达式判断的。

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

    répondre
    0
  • Annulerrépondre