用C语言的三重循环统计输入的一行字符中的英文字母、空格、数字和其它字符的个数
时间: 2024-04-30 19:23:51 浏览: 11
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char c;
int letter_count = 0, space_count = 0, digit_count = 0, other_count = 0;
while ((c = getchar()) != '\n') {
if (isalpha(c)) { // 英文字母
letter_count++;
} else if (isspace(c)) { // 空格
space_count++;
} else if (isdigit(c)) { // 数字
digit_count++;
} else { // 其他字符
other_count++;
}
}
printf("Letter count: %d\n", letter_count);
printf("Space count: %d\n", space_count);
printf("Digit count: %d\n", digit_count);
printf("Other count: %d\n", other_count);
return 0;
}
```
相关问题
用c语言的循环语句输入一行字符分别统计出其中英文字母空格数字和其他字符的个数
使用C语言的循环语句可以输入一行字符并统计其中英文字母、空格、数字和其他字符的个数。下面是一个示例代码:
```c
#include <stdio.h>
int main() {
char c;
int ch, s, d, o;
ch = 0;
s = 0;
d = 0;
o = 0;
while ((c = getchar()) != '\n') {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
ch++;
else if (c == ' ')
s++;
else if (c >= '0' && c <= '9')
d++;
else
o++;
}
printf("char=%d space=%d digit=%d others=%d\n", ch, s, d, o);
return 0;
}
```
该代码使用了一个while循环来读取输入的字符,然后使用if语句来判断字符的类型并相应地增加计数器的值。最后,使用printf函数输出统计结果。
输入一行字符分别统计英文字母空格数字和其他字符的个数用C语言
以下是一个简单的 C 语言程序,可以输入一行字符并统计其中英文字母、空格、数字和其他字符的个数。
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, alpha, space, digit, other;
printf("请输入一行字符:\n");
fgets(str, sizeof(str), stdin);
alpha = space = digit = other = 0;
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
alpha++;
} else if (isspace(str[i])) {
space++;
} else if (isdigit(str[i])) {
digit++;
} else {
other++;
}
}
printf("英文字母个数:%d\n", alpha);
printf("空格个数:%d\n", space);
printf("数字个数:%d\n", digit);
printf("其他字符个数:%d\n", other);
return 0;
}
```
在程序中,我们定义了一个字符数组 `str`,用于存储输入的一行字符。然后,我们定义了四个变量 `alpha`、`space`、`digit` 和 `other`,分别表示英文字母、空格、数字和其他字符的个数,初始化为 0。
接下来,我们使用 `fgets()` 函数从标准输入中读取一行字符,并将其存储在 `str` 中。然后,我们使用一个循环来遍历这个字符串,对于每个字符,我们使用 `isalpha()`、`isspace()` 和 `isdigit()` 函数来判断它是英文字母、空格还是数字。如果不是这三种字符,则为其他字符。
最后,我们输出统计结果,即英文字母、空格、数字和其他字符的个数。
注意:上述程序中使用了 C 标准库中的 `isalpha()`、`isspace()` 和 `isdigit()` 函数,需要包含头文件 `<ctype.h>`。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)