C++统计数字字符个数
时间: 2024-06-13 20:06:51 浏览: 15
以下是两种C++统计数字字符个数的例子:
1.使用getline()函数读入整行字符串,遍历字符串中的每个字符,判断是否为数字字符,如果是则计数器加1,最后输出计数器的值。
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string arr;
getline(cin, arr);
int a = 0;
for(int i = 0; i < arr.length(); i++){
if(arr[i] >= 48 && arr[i] <= 57){
a++;
}
}
cout << a;
return 0;
}
```
2.使用gets()函数读入整行字符串,遍历字符串中的每个字符,判断是否为数字字符,如果是则计数器加1,最后输出计数器的值。
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char arr[100];
gets(arr);
int len = strlen(arr);
相关问题
用c++统计数学字符个数
以下是用C语言实现统计数学字符个数的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, count = 0;
printf("请输入一个字符串:");
gets(str);
for (i = 0; str[i] != '\0'; i++) {
if (isalnum(str[i]) || str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/' || str[i] == '^' || str[i] == '(' || str[i] == ')' || str[i] == '.') {
count++;
}
}
printf("数学字符个数为:%d\n", count);
return 0;
}
```
该程序首先提示用户输入一个字符串,然后使用`gets()`函数将其存储在字符数组`str`中。接着使用`for`循环遍历字符串,如果当前字符是字母、数字或数学运算符(+、-、*、/、^、(、)、.)中的一种,就将计数器`count`加1。最后输出计数器的值即可。
需要注意的是,该程序只能统计单个字符,如果要统计一个字符串中数学字符的总数(如`2+3*4-5/6`中的数学字符数为7),需要对字符串进行分割和计算。
oj1129统计数字字符个数
这是一道简单的字符串处理题目。题目要求我们统计给定字符串中数字字符出现的次数。
我们可以遍历字符串中的每一个字符,判断它是否是数字字符。如果是,则计数器加一。最后输出计数器的值即可。
以下是示例代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
getline(cin, str); // 输入字符串
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (isdigit(str[i])) { // 判断字符是否为数字字符
count++;
}
}
cout << count << endl; // 输出数字字符的个数
return 0;
}
```
希望可以帮助你解决这道问题。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)