Home > Article > Backend Development > Input a string of characters in C++, how to count the number of numbers in it and output it
The following steps can be used to count the number of digits in a string in C: traverse the characters in the string. Use the isdigit() function to check if the current character is a digit. If it is a number, add 1 to the number counter.
How to count the number of numbers in a string in C
To count the number of numbers in a string number, you can use the following steps:
Traverse each character in the string
for
A loop or iterator to iterate through the characters in a string one by one. Check whether the current character is a digit
isdigit()
function to check the current character Whether it is a number. If the current character is a digit, increment the digit counter
isdigit()
If the function returns true
, the digital counter will be incremented by 1. The following is a C code example:
<code class="cpp">#include <iostream> #include <string> using namespace std; int main() { string input; int numCount = 0; cout << "Enter a string: "; getline(cin, input); for (int i = 0; i < input.length(); i++) { if (isdigit(input[i])) { numCount++; } } cout << "The number of digits in the string is: " << numCount << endl; return 0; }</code>
This program will prompt the user for a string and then iterate through each character in the string. If a character is a number, it will increment the number counter. Finally, it will print the number of digits in the string.
The above is the detailed content of Input a string of characters in C++, how to count the number of numbers in it and output it. For more information, please follow other related articles on the PHP Chinese website!