酷代码 AI
菜单
服务商

我国就业情况解析:数据排序与查询程序及开发注意要点

```c #include <stdio.h> #include <stdlib.h> #include <string.h> // 定义一个结构体来存储省市名称和就业人数 typedef struct { char name[50]; int population; } Province; // 交换两个Province结构体变量的值 void swap(Province *a, Province *b) { Province temp = *a; *a = *b; *b = temp; } // 冒泡排序函数,对Province数组进行降序排序 void bubbleSort(Province arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j].population < arr[j + 1].population) { swap(&arr[j], &arr[j + 1]); } } } } // 主函数 int main() { FILE *inputFile, *outputFile; Province provinces[100]; int count = 0; char query[50]; // 打开输入文件 inputFile = fopen("employ-data.txt", "r"); if (inputFile == NULL) { printf("无法打开输入文件。\n"); return 1; } // 从输入文件中读取数据 while (fscanf(inputFile, "%s %d", provinces[count].name, &provinces[count].population) != EOF) { count++; } fclose(inputFile); // 对数据进行降序排序 bubbleSort(provinces, count); // 打开输出文件 outputFile = fopen("employ-sort.txt", "w"); if (outputFile == NULL) { printf("无法打开输出文件。\n"); return 1; } // 在屏幕上显示排序后的数据,并将其写入输出文件 for (int i = 0; i < count; i++) { printf("%s %d\n", provinces[i].name, provinces[i].population); fprintf(outputFile, "%s %d\n", provinces[i].name, provinces[i].population); } fclose(outputFile); // 循环进行查询操作 while (1) { printf("请输入要查询的省市名称(输入'退出'结束查询):"); scanf("%s", query); if (strcmp(query, "退出") == 0) { break; } int found = 0; for (int i = 0; i < count; i++) { if (strcmp(provinces[i].name, query) == 0) { printf("查询到的就业人数为:%d\n", provinces[i].population); found = 1; break; } } if (!found) { printf("查询不成功\n"); } } return 0; } ``` 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: 1. 文件操作时要检查文件是否成功打开,避免因文件打开失败而导致程序崩溃。 2. 字符串比较时要使用`strcmp`函数,不能直接用`==`进行比较。 3. 循环查询时要注意退出条件的设置,避免陷入无限循环。 ######[AI写代码神器 | 791点数解答 | 2025-12-01 00:03:22]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]