C语言 输入一行字符,用指针使用fgets函数分别统计出其中英文字母、空格、数字和其他字符的个数
时间: 2024-05-02 19:21:29 浏览: 14
```
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[100];
int letters = 0, spaces = 0, digits = 0, others = 0;
printf("请输入一行字符:");
fgets(str, 100, stdin);
char *p = str;
while (*p != '\0')
{
if (isalpha(*p)) // 判断是否为字母
letters++;
else if (isspace(*p)) // 判断是否为空格
spaces++;
else if (isdigit(*p)) // 判断是否为数字
digits++;
else
others++;
p++;
}
printf("英文字母个数:%d\n空格个数:%d\n数字个数:%d\n其他字符个数:%d\n", letters, spaces, digits, others);
return 0;
}
```
相关问题
用C语言编写输入一行字符,分别统计出其中英文字母、数字和其它字符的个数,采用指针操作完成上述工作
好的,下面是C语言代码:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *str, int *letters, int *digits, int *others) {
while (*str != '\0') {
if (isalpha(*str))
(*letters)++;
else if (isdigit(*str))
(*digits)++;
else
(*others)++;
str++;
}
}
int main() {
char str[100];
int letters = 0, digits = 0, others = 0;
printf("请输入一行字符:");
fgets(str, 100, stdin);
count_chars(str, &letters, &digits, &others);
printf("字母个数:%d\n数字个数:%d\n其他字符个数:%d\n", letters, digits, others);
return 0;
}
```
在函数`count_chars`中,使用指针来修改`letters`、`digits`和`others`的值,最终在`main`函数中输出它们的值。注意使用`fgets`函数来读取输入的一行字符,而不是`scanf`,因为`scanf`会在遇到空格或换行符时停止读取。
输入一行文字,用指针的方法统计其中大写字母,小写字母,空格,数字以及其他字符的个数利用c语言
下面是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h> // 包含了用于字符判断的函数,如 isdigit, isalpha 等
int main() {
char str[100];
int upper = 0, lower = 0, space = 0, digit = 0, other = 0;
char *p;
printf("请输入一行文字:\n");
fgets(str, 100, stdin); // 使用 fgets 函数读取一行文字
p = str; // 指向字符串的第一个字符
while (*p != '\0') { // 如果没有到字符串末尾
if (isupper(*p)) { // 判断是否为大写字母
upper++;
} else if (islower(*p)) { // 判断是否为小写字母
lower++;
} else if (isspace(*p)) { // 判断是否为空格
space++;
} else if (isdigit(*p)) { // 判断是否为数字
digit++;
} else { // 其他字符
other++;
}
p++; // 指向下一个字符
}
printf("大写字母:%d\n", upper);
printf("小写字母:%d\n", lower);
printf("空格:%d\n", space);
printf("数字:%d\n", digit);
printf("其他字符:%d\n", other);
return 0;
}
```
代码中使用指针 p 指向字符串的第一个字符,然后遍历整个字符串,判断每个字符的类型,统计出现的次数。注意,这里使用了 ctype.h 库中的一些函数,可以方便地进行字符判断。
相关推荐
![](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)