C语言ISDIGIT用法

2024-11-08 22:36:12
推荐回答(3个)
回答1:

#include 
#include 
#define LINELEN 80
#define MAXMUNLEN 20
int main(int argc, char *argv[])
{
    char buffer[LINELEN];
    char number[MAXMUNLEN];//记录有效数据 
    char *fgets_rtn = NULL;
    char *num_ptr=number;
    int ch,
    isnum=0,//是否有效标记 
    sig=0,//正负号标记 
    num=0,//数字标记 
    poin=0;//小数点标记 
    while ((fgets_rtn=fgets(buffer, LINELEN, stdin))!=NULL)
    {
        if (*fgets_rtn=='\n')break;//空行退出
        while ((ch=*fgets_rtn++)!='\0')//检测每个字符
        {
            switch (ch)
            {
            case '\n':ch='\0';break;//是有效数据跳过回车符结束 
            case '+':
            case '-':
                if (sig) 
                    isnum=0;//下同无效数据
                else
                {
                    if(num||poin)
                        isnum=0;
                   else//未标记 ,下同 
                  {
                       sig++;
                       isnum++;              
                   }
                }
                break;
            case '.':
                if(poin)
                    isnum=0;
                else
                {
                    poin++;
                   isnum++;
                }
                break;
            default:
                if (isdigit(ch))
                {
                    num++;
                    isnum++;
                }
                else if (isspace(ch))
                {
                    if(isnum)
                       isnum=0;
                }
                else
                {
                    num++;  //设置无效数据 
                    isnum=0;
                }                    
                break;
            }//end switch
            
            if (isnum)//如果是有效字符,写入number数据 
                *num_ptr++=ch;
            else
            {
                if(sig||poin||num)
                {
                    *num_ptr='\0';
                    break;//结束本次检测
                }
            }
        }//end while
        
        if (isnum&&num)//判断 
            if (poin)
                printf("%s为有效double型!\n",number);
            else
                printf("%s为有效整型!\n",number);
        else
        {
            //printf("%s为无效数据!\n",buffer);//会输出回车符,不完善。 
            fgets_rtn=buffer;
            while((ch=*fgets_rtn++)!='\n'&&ch!='\0')
                putchar(ch);//如果不能用putchar用://printf("%c",ch); 
            printf("为无效数据!\n");
        }
  
        isnum=sig=num=poin=0;//置0
        num_ptr=number;
        *num_ptr='\0';
    }//end while
    
    return 0;
}

回答2:

抽出来判断部分。

int isValidInt(char* str)
{
    while (isspace(str) || *str == '\0')
        ++str;
    
    if (*str == '\0')
        return 0;
    
    if (*str == '+' || *str == '-')
        ++str;
        
    while (*str != '\0')
    {
        if (!isdigit(*str))
            return 0;
        ++str;
    }
    
    return 1;
}

大概这样。

回答3:

判断一个数是否是数字,isdigit(),在括号中写上需要判断的变量就行了