如何检查一个给定的字符串仅包含数字或不是在C [关闭]

问题描述 投票:5回答:2

如何检查一个给定的字符串仅包含数字或不是?

c
2个回答
15
投票

您可以使用isdigit()宏来检查,如果一个字符是数字。利用这一点,你可以很容易地编写检查仅包含数字的字符串的函数。

#include <ctype.h>

int digits_only(const char *s)
{
    while (*s) {
        if (isdigit(*s++) == 0) return 0;
    }

    return 1;
}

超小型文体旁注:为空字符串返回true。您可能会或可能不希望这种行为。


-2
投票
#include<stdio.h>
void main()
{
    char str[50];
    int i,len = 0,count = 0;
    clrscr();
    printf("enter any string:: ");
    scanf("%s",str);
    len = strlen(str);
    for(i=0;i<len;i++)
    {
            if(str[i] >= 48 && str[i] <= 57)    
            {
                  count++;
            }
    }
    printf("%d outoff %d numbers in a string",count,len);
    getch();
}
© www.soinside.com 2019 - 2024. All rights reserved.