Home  >  Article  >  Backend Development  >  Input a string of characters in C++, how to count the number of numbers in it and output it

Input a string of characters in C++, how to count the number of numbers in it and output it

下次还敢
下次还敢Original
2024-05-09 04:18:151101browse

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.

Input a string of characters in C++, how to count the number of numbers in it and output it

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:

  1. Traverse each character in the string

    • Use for A loop or iterator to iterate through the characters in a string one by one.
  2. Check whether the current character is a digit

    • Use the isdigit() function to check the current character Whether it is a number.
  3. If the current character is a digit, increment the digit counter

    • if isdigit() If the function returns true, the digital counter will be incremented by 1.
  4. Repeat steps 2 and 3 until the entire string is traversed

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn