如何检查给定的字符串只包含C中的数字

时间:2013-01-20 08:14:11

标签: c

如何检查给定字符串是否只包含数字?

2 个答案:

答案 0 :(得分:15)

您可以使用isdigit()宏来检查字符是否为数字。使用它,您可以轻松编写一个函数来检查字符串是否只包含数字。

#include <ctype.h>

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

    return 1;
}

超小型文体旁注:对于空字符串返回true。您可能想要也可能不想要这种行为。

答案 1 :(得分:-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();
}