C++ bootcamp · Lab 43

Count the digits

easyStrings8 minLesson: 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.

std::isdigit from <cctype> 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. std::getline so spaces survive.
  2. if (std::isdigit((unsigned char)ch)) count++;
Show correct code

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

#include <iostream>
#include <string>
#include <cctype>

int main() {
  std::string line;
  std::getline(std::cin, line);
  int count = 0;
  for (char ch : line) {
    if (std::isdigit((unsigned char)ch)) count++;
  }
  std::cout << count << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.