【问题标题】:Disabling characters other than numbers in scanf in C在C中的scanf中禁用数字以外的字符
【发布时间】:2012-11-13 10:58:42
【问题描述】:

我遇到的问题是我想禁止用户在我的程序中放置字符而不是数字,并可选择打印“它已禁用”消息。它应该询问相同变量的值。我试图这样做:

scanf(" %[0-9]d",&x);

还有这个:

else
       result = scanf("%*s");

但它仍然不起作用。我应该寻找什么?我搜索了互联网,但我只找到了使用 cin 的 C++ 解决方案,不幸的是它在 C 中根本不起作用。

【问题讨论】:

    标签: c char character scanf


    【解决方案1】:

    你可以试试这样的:

    char c[SIZE];
    int i;    
    
    // While the string is not a number
    while(fgets(c, SIZE , stdin) && !isAllDigit(c));  
    

    isAllDigit 在哪里:

    int isAllDigit(char *c){
        int i;
        for(i = 0; c[i] != '\0' && c[i] != '\n'; i++) // Verify if each char is a digit
           if(!isdigit(c[i]))         // if it this char is not a digit
               return 0;              // return "false"
    
        return 1; // This means that the string is a number       
    } 
    

    【讨论】:

      【解决方案2】:

      scanf 不再使用太多,因为它完全不适合键盘输入。现在的基本方案是循环执行 fgets() + validate + sscanf()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-24
        • 1970-01-01
        • 2017-04-03
        • 2018-12-16
        相关资源
        最近更新 更多