Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • C

Idiom #137 Check if string contains only digits

Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.

#include <ctype.h>
#include <stdbool.h>
#include <string.h>
bool b = true;
const int n = strlen(s);
for (int i = 0; i < n; ++i) {
  if (!isdigit(s[i])) {
    b = false;
    break;
  }
}
#include <string.h>
char b = 0;
int n = strlen(s);
for (int i = 0; i < n; i++) {
	if (! (b = (s[i] >= '0' && s[i] <= '9')))
		break;
}
B := (for all Char of S => Char in '0' .. '9');

New implementation...
< >
programming-idioms.org