Number of Digits
Lesson 5 of 5 in Coddy's Simple Character Counter using C++ course.
In C++, you can check if a character is a digit using:
bool b = std::isdigit(c)b will hold true if c is a digit, otherwise false.
Or, in short, using namespace:
bool b = isdigit(c)Challenge
EasyAdd to your existing program, count the number of digits at the string, and output it at the end like this (with a new line):
Number of digits: XXDon't delete the previous output, output it after your current outputs.
Check the test cases for examples!
Try it yourself
#include <iostream>
#include <string>
using namespace std;
int main() {
string text;
cout << "Enter text:" << endl;
getline(cin, text);
int total = 0;
int totalLetters = 0;
for (char c : text) {
if (c == ' ') {
continue;
}
total++;
if (isalpha(c)) {
totalLetters++;
}
}
cout << "Total characters: " << total << endl;
cout << "Total letters: " << totalLetters << endl;
return 0;
}