11

How to check a given string contains only number or not?

DNU Dev
  • 127
  • 1
  • 1
  • 3

2 Answers2

24

You can use the isdigit() macro to check if a character is a number. Using this, you can easily write a function that checks a string for containing numbers only.

#include <ctype.h>

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

    return 1;
}

Subminiature stylistic sidenote: returns true for the empty string. You might or might not want this behavior.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 2
    Considering the other answer so far, that was well worth posting after all ;-) – Clifford Jan 20 '13 at 10:38
  • @Clifford Yeah, pretty much :P –  Jan 20 '13 at 10:39
  • 2
    If you don't want to use `ctype.h` and `isdigit()`, just test for `if(*s<'0' || *s>'9')`. The C-standard guarantees that `c - '0'` has the characters numeric value for any character `c` that is a digit. That is true even for Unicode character sets. – con-f-use Apr 19 '16 at 12:46
  • 1
    This function returns `true` for empty string. – viator May 24 '20 at 13:53
  • You could change the algo to consider floats too. For example 2343.34 should also return true. `int digits_only(const char *s) { while (*s) { if(*s == '.') { *s++; continue; } else if ((isdigit(*s++) == 0)) return 0; } return 1; }` – Vendetta V Dec 22 '20 at 16:08
  • `int digits_only(const char *s) { if(*s == '0') return 0; while (*s) { if(*s>='0' && *s<='9'){ s++; } else return 0; } return 1; }` – Max Oct 12 '22 at 17:04
-4
#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();
}
shivtej
  • 633
  • 9
  • 18
  • 3
    `void main()` in 2013? Really? "`str[i]>=48 && str[i]<=57`" isn't exactly the right way to do that part either. – Flexo Jan 20 '13 at 09:59
  • 1
    Too much superfluous (and compiler specific) code for others to criticise and down-vote see H2CO3's answer - short and to the point, with no unnecessary extras. Also this counts the number of ASCII digit characters (in a somewhat obfuscated manner); that is not what the question is about. Sure you could test `count != len`, but as a go/no-go test it is sufficient to stop on first non-digit character. The "magic numbers" 48 and 57 could more intuitively be replaced with the caharacter constants `'0'` and `'9'`. – Clifford Jan 20 '13 at 10:32
  • I know my dear friend but i post simple answer for the problem. And i hope this is the best solution to those who beginner of c programming – Programmingcampus.com Jan 20 '13 at 12:11