经典说说大全-经典句子大全-灵儿心情网

经典说说大全-经典句子大全-灵儿心情网

c语言统计名字如何编写

59

```c

include

include

include

define MAX_NAME_LENGTH 100

define MAX_USERS 1000

// 定义结构体存储姓名及出现次数

typedef struct {

char name[MAX_NAME_LENGTH];

int count;

} NameCount;

int main() {

NameCount *data = NULL;

int total = 0, i, capacity = 10;

// 动态分配初始内存

data = (NameCount *)malloc(capacity * sizeof(NameCount));

if (!data) {

printf("内存分配失败

");

return 1;

}

printf("输入姓名(输入空行结束):

");

char temp;

while (1) {

if (fgets(temp, sizeof(temp), stdin) == NULL) break; // 输入结束

temp[strcspn(temp, "

")] = 0; // 去除换行符

int found = 0;

for (i = 0; i < total; i++) {

if (strcmp(data[i].name, temp) == 0) {

data[i].count++;

found = 1;

break;

}

}

if (!found) {

if (total >= capacity) {

capacity *= 2;

NameCount *temp_data = (NameCount *)realloc(data, capacity * sizeof(NameCount));

if (!temp_data) {

printf("内存扩展失败

");

free(data);

return 1;

}

}

strcpy(data[total].name, temp);

data[total].count = 1;

total++;

}

}

// 输出统计结果

printf("

姓名\t出现次数

");

for (i = 0; i < total; i++) {

printf("%-20s\t%d

", data[i].name, data[i].count);

}

// 释放内存

free(data);

return 0;

}

```

代码说明:

结构体定义

使用`struct NameCount`存储姓名和出现次数,包含字符数组`name`(最大长度100)和整型计数器`count`。

动态内存管理

初始分配10个元素的内存,若不足则动态扩展(每次翻倍)。

使用`malloc`分配内存,`realloc`调整大小,`free`释放内存。

输入处理

使用`fgets`读取输入,`strcspn`去除换行符。

通过`strcmp`判断姓名是否已存在,若存在则增加计数,否则添加新记录。

输出结果

按姓名排序后输出每个姓名及其出现次数。

注意事项:

输入验证:

此程序未对输入的姓名长度进行严格限制,实际应用中需添加长度检查以避免缓冲区溢出。

性能优化:对于大规模数据,建议使用哈希表或排序算法(如快速排序)提高效率。

通过以上步骤,可以灵活统计多个姓名的出现次数,并处理动态输入场景。