C++ 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
时间: 2023-11-25 18:02:49 浏览: 81
好的,我来回答你的问题。这个问题可以通过循环读入每个字符,判断它属于哪种类型来实现。具体实现代码如下:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char ch;
int letter_cnt = 0, space_cnt = 0, digit_cnt = 0, other_cnt = 0;
printf("请输入一行字符:\n");
while ((ch = getchar()) != '\n') {
if (isalpha(ch))
letter_cnt++;
else if (isspace(ch))
space_cnt++;
else if (isdigit(ch))
digit_cnt++;
else
other_cnt++;
}
printf("其中有英文字母%d个,空格%d个,数字%d个,其他字符%d个。\n", letter_cnt, space_cnt, digit_cnt, other_cnt);
return 0;
}
```
这个程序会先输出提示信息,然后使用 `getchar` 来逐个读入输入的字符,并使用 if 语句来判断它的类型,最后输出统计结果。
希望我的解答能对你有所帮助!
相关问题
用c++输入一行字符 分别统计出其中的英文字母,空格,数字和其他字符的个数
```c++
#include<iostream>
using namespace std;
int main(){
char ch;//定义字符变量
int letter = 0, space = 0, digit = 0, other = 0;//分别统计英文字母、空格、数字和其他字符的个数
cout<<"请输入一行字符:";
while(cin.get(ch)){//不断循环输入字符,直到输入结束
if(ch>='a' && ch<='z' || ch>='A' && ch<='Z'){//判断是否为英文字母
letter++;
}
else if(ch==' '){//判断是否为空格
space++;
}
else if(ch>='0' && ch<='9'){//判断是否为数字
digit++;
}
else{//其他字符
other++;
}
if(ch=='\n'){//遇到换行符结束循环
break;
}
}
cout<<"英文字母个数:"<<letter<<endl;
cout<<"空格个数:"<<space<<endl;
cout<<"数字个数:"<<digit<<endl;
cout<<"其他字符个数:"<<other<<endl;
return 0;
}
```
用c++输入一行字符,分别统计其中英文字母、空格、数字和其他字符的个数
好的,这个问题可以回答。请看下面的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, letters = , spaces = , digits = , others = ;
printf("请输入一行字符:\n");
fgets(str, 100, stdin);
for (i = ; str[i] != '\'; i++) {
if (isalpha(str[i])) {
letters++;
} else if (isspace(str[i])) {
spaces++;
} else if (isdigit(str[i])) {
digits++;
} else {
others++;
}
}
printf("字母个数:%d\n", letters);
printf("空格个数:%d\n", spaces);
printf("数字个数:%d\n", digits);
printf("其他字符个数:%d\n", others);
return ;
}
```
希望这个回答能够帮到你。
阅读全文
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)