33,311
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct student /*包含学生姓名和成绩*/
{
char name[16];
int english;
int math;
};
#define MAX_SIZE 100
int main()
{
FILE *fp1 = fopen("db1.txt", "r");
if (!fp1)
exit(0);
FILE *fp2 = fopen("db2.txt", "r");
if (!fp2)
exit(0);
FILE *fp3 = fopen("db3.txt", "w");
if (!fp3)
exit(0);
struct student info[MAX_SIZE] = { 0 };
char name[32];
int ret, score;
int i = 0, num;
while (!feof(fp1))
{
ret = fscanf(fp1, "%s %d\n", name, &score);
if (ret < 2)
break;
//printf("1. name = %s, score = %d\n", name, score);
strcpy(info[i].name, name);
info[i].english = score;
i++;
if (i >= MAX_SIZE)
break;
}
fclose(fp1);
num = i;
i = 0;
while (!feof(fp2))
{
ret = fscanf(fp2, "%s %d\n", name, &score);
if (ret < 2)
break;
//printf("2. name = %s, score = %d\n", name, score);
while (i < num) {
if (strcmp(info[i].name, name) == 0) {
info[i].math = score;
break;
}
i++;
}
if (i >= num && i < MAX_SIZE) {
strcpy(info[i].name, name);
info[i].math = score;
num++;
}
if (num >= MAX_SIZE)
break;
i = 0;
}
fclose(fp2);
//printf("Num = %d\n", num);
i = 0;
while (i < num) {
fprintf(fp3, "%s %d %d %.1lf\n",
info[i].name,
info[i].english,
info[i].math,
(info[i].english + info[i].math)*1.0 / 2);
i++;
}
fclose(fp3);
return 0;
}
上面的代码确实有点问题,这个是测试过的。参考一下吧
遇到问题不要慌,不要马上就问,自己先试试找问题,不然自己怎么能进步呢?!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct student /*包含学生姓名和成绩*/
{
char name[16];
int english;
int math;
};
#define MAX_SIZE 100
int main()
{
FILE *fp1 = fopen("db1.txt", "r");
if (!fp1)
exit(0);
FILE *fp2 = fopen("db2.txt", "r");
if (!fp2)
exit(0);
FILE *fp3 = fopen("db3.txt", "w"); /*db3.txt将被创建*/
if (!fp3)
exit(0);
struct student info[MAX_SIZE] = { 0 };
char name[32];
int ret, score;
int i = 0, num;
while (!feof(fp1))
{
ret = fscanf(fp1, "%s %d\n", name, &score);
if (ret < 2)
break;
strcpy(info[i].name, name);
info[i].english = score;
i++;
if (i >= MAX_SIZE)
break;
}
fclose(fp1);
num = i;
i = 0;
while (!feof(fp2))
{
ret = fscanf(fp2, "%s %d\n", name, &score);
if (ret < 2)
break;
while (i < num)
if (strcmp(info[i].name, name) == 0)
info[i].math = score;
if (i >= num && i < MAX_SIZE) {
strcpy(info[i].name, name);
info[i].math = score;
num++;
}
if (num >= MAX_SIZE)
break;
i = 0;
}
fclose(fp2);
i = 0;
while (i < num) {
fprintf(fp3, "%s %d %d %.1lf\n",
info[i].name,
info[i].english,
info[i].math,
(info[i].english + info[i].math)*1.0 / 2);
i++;
}
fclose(fp3);
return 0;
}
参考一下吧
问题较多,建议对比找一下;比如两个while循环都是从文件1里读取,这个错误不应该呢,不够仔细。
程序异常退出的直接原因是name是野指针,没有给其分配空间,建议直接用数组即可。