首页 > 解决方案 > 替代 isdigit 来读取大于 9 的数字?

问题描述

我目前正在使用 C 语言编写一个程序,该程序使用scanf. 我希望程序终止是用户输入了数字以外的内容。

目前,我正在使用以下代码:

 while(scanf("%c", &value) == 1) {
       if(isdigit(value)) {
          scanf("%c", &value);
          push(&head, value);
          count++;
     }
     else {
       break;
     }
   }

isdigit用来检查输入是否是 0-9 之间的数字,但如果用户要输入类似“52”的内容,这会带来问题。

有没有替代方案isdigit可以处理这个问题?任何意见,将不胜感激!

标签: cwhile-loop

解决方案


您不能将“52”存储到 char 而不是试试这个,

#include <stdio.h>
#include <ctype.h>


int myisdigit(char *str)
{
    while(*str)
    {
        if(!isdigit(*str))
            return 0;

        str++;
    }

    return 1;
}

int main()
{
    char str[10];

    scanf("%s",str);

    if(myisdigit(str))
        printf("digit");
    else
        printf("non digit");

    return 0;
}

您也可以将 myisdigit 更改为

int myisdigit(char *str)
{

    while(*str)
    {
        if( ! ( ( ( *str ) >= '0' ) && ( (*str) <='9' ) ) )
            return 0;

        str++;
    }

    return 1;
}

推荐阅读