C bootcamp · Lab 41

Count the digits

easyStrings8 minLesson: C Strings

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read one line of text and print how many digit characters (0–9) it contains.

isdigit from ctype.h tests one character. Cast to unsigned char first.

Input. One line of text.

Output. One integer: the digit count.

Examples

Example 1
Input
ab12c3
Output
3
Example 2
Input
hello
Output
0
Hint
  1. Read with fgets or getchar until newline.
  2. if (isdigit((unsigned char)c)) count++;
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>
#include <ctype.h>

int main(void) {
  int c, count = 0;
  while ((c = getchar()) != EOF && c != '\n') {
    if (isdigit((unsigned char)c)) count++;
  }
  printf("%d\n", count);
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.