如何读取用户的输入。C语言中可以用gets或者fgets函数,但gets不安全,容易导致缓冲区溢出,所以最好用fgets。不过用户输入的是“一行”字符串,所以可能需要处理换行符的问题。
例如,在读取输入后,检查最后一个字符是否是换行符,如果是,则将其替换为'\0',从而避免统计它。
接下来,如何统计各个类型的字符。需要四个计数器:字母、数字、空格、其他。初始化这四个变量为0。然后遍历字符串中的每个字符,直到遇到'\0'。
字母:可以用isalpha函数,或者自己判断,例如c >= 'a' && c <= 'z' 或者 c >= 'A' && c <= 'Z'。使用ctype.h中的isalpha函数更方便。
数字:isdigit函数,或者c >= '0' && c <= '9'。
空格:c == ' '。
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[1000];
int letters = 0, digits = 0, spaces = 0, others = 0;//定义数组
printf("请输入一行字符串");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\n'; i++)
{
if (isalpha(str[i]))
{
letters++;
}
else if (isdigit(str[i]))
{
digits++;
}
else if (isspace(str[i]))
{
spaces++;
}
else
{
others;
}
}
printf("字母%d ,数字%d,空格%d,其他%d", letters, digits, spaces, others);
return 0;
}