C语言程序设计练习题,附详细代码与解题思路


题目

编写一个C语言程序,实现以下功能:

1. 从用户输入中读取一个字符串,并统计该字符串中字母、数字、空格和其他字符的数量。

2. 输出统计结果。

解题思路

1. 定义变量:定义四个变量,分别用于存储字母、数字、空格和其他字符的数量。

2. 遍历字符串:使用循环遍历输入的字符串。

3. 判断字符类型:对于每个字符,使用条件语句判断其类型,并相应地增加对应变量的值。

4. 输出结果:输出字母、数字、空格和其他字符的数量。

示例代码

c

include

include

int main() {

char str[100];

int letters = 0, digits = 0, spaces = 0, others = 0;

printf("请输入一个字符串:");

fgets(str, 100, stdin);

for (int i = 0; str[i] != '\0'; i++) {

if (isalpha(str[i])) {

letters++;

} else if (isdigit(str[i])) {

digits++;

} else if (isspace(str[i])) {

spaces++;

} else {

others++;

}

}

printf("字母数量:%d", letters);

printf("数字数量:%d", digits);

printf("空格数量:%d", spaces);

printf("其他字符数量:%d", others);

return 0;

}

解题说明

1. 程序首先定义了一个字符数组`str`用于存储用户输入的字符串,以及四个整型变量`letters`、`digits`、`spaces`和`others`用于统计不同类型字符的数量。

2. 使用`printf`函数提示用户输入一个字符串,并使用`fgets`函数从标准输入读取字符串。

3. 使用`for`循环遍历字符串中的每个字符。

4. 对于每个字符,使用`isalpha`、`isdigit`和`isspace`函数判断其类型,并相应地增加对应变量的值。如果字符不是字母、数字或空格,则将其归类为其他字符。

5. 使用`printf`函数输出统计结果。

注意:在实际编程中,还需要考虑输入字符串的长度、可能的错误输入等情况,以确保程序的健壮性和可靠性。