//以下是一个统计用户输入字符串中字符个数的C语言程序。该程序包含详细的注释和说明。
#include <stdio.h>
#include <string.h>
int main() {
char string[100];
int count;
// 请求用户输入一个字符串
printf("Enter a string: ");
fgets(string, 100, stdin);
// 使用strlen函数计算字符串长度
count = strlen(string) - 1; // We subtract 1 to not count the '\n' character (newline) which is included when using fgets
// 打印字符数量
printf("Number of characters in the string is: %d\n", count);
return 0;
}
//这段C语言代码实现了统计用户输入字符串中字符个数的功能。
//当程序开始运行时,我们首先定义了一个字符数组 'string[100]' 以存储用户的输入和一个整型变量 'count' 用于计数字符的数量。
//`fgets` 函数用来从标准输入读取100个字符或直到碰到换行符或 EOF,取决于哪个先出现,并且将读取的结果存储在 'string' 数组中。
//`strlen(string)` 函数是一个库函数,用于计算字符串 'string' 的长度(不包括末尾的 '\0' 字符)。这项操作的结果被赋值给 'count' 变量。
//最后,我们用 `printf` 函数打印输出字符的数量。注意我们在计算字符数量时减去 1,那是 'fgets' 函数在读取字符串到达行末时会将 '\n' 添加到字符串末尾。