【发布时间】:2015-03-08 08:49:35
【问题描述】:
我的问题是对从 txt 文件中提取的一些数字进行排序。 当我编译文件时,程序停止工作。
#include <stdio.h>
#include <stdlib.h>
struct student_grades{
int number;
char name[10];
char surname[10];
int grade;
};
typedef struct student_grades stgrade;
void bubble_sort(int list[], int n){ //Line 16
long c, d, t;
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (list[d] > list[d+1])
{
/* Swapping */
t = list[d];
list[d] = list[d+1];
list[d+1] = t;
}
}
}
}
int main()
{
int i=0;
FILE *stu; // file tipinde değişken tutacak
FILE *stub;
stu= fopen("student.txt","r");
stub= fopen("stu_order.txt","a");
stgrade stg[12];
if(stu!=NULL){
while(!feof(stu))
{
fscanf(stu,"%d",&stg[i].number);
fscanf(stu,"%s",stg[i].name);
fscanf(stu,"%s",stg[i].surname);
fscanf(stu,"%d",&stg[i].grade);
//fprintf(stub,"%d %s %s %d\n",stg[i].number,stg[i].name,stg[i].surname,stg[i].grade);
++i;
}
bubble_sort(stg->number,12); //Line 59
fprintf(stub,"%d %s %s %d\n",stg[1].number,stg[1].name,stg[1].surname,stg[1].grade); //control that is bubble success?
}
else
printf("File Not Found");
fclose(stu);
fclose(stub);
return 0;
一开始我写了第 59 行
bubble_sort(stg.number,12);
像这样。但它会出错并且无法编译。我用
改变它bubble_sort(stg->number,12);
它已编译但停止工作并收到警告
格式化输出:
在函数'main'中:
59 3 [警告] 传递 'bubble_sort' 的参数 1 使指针从整数而不进行强制转换 [默认启用]
16 6 [注意] 预期为 'int *' 但参数的类型为 'int'
学生.txt
80701056 Sabri Demirel 45
52801022 Burak Erkin 68
13801045 Umut Korkmaz 88
74801334 Semih Potuk 58
15678544 Enes Sezer 76
42125884 Ahmet Can 84
12355488 Emre Ozdemir 47
18744125 Ugur Yildiz 64
62184111 Mustafa Ozturk 80
18412548 Ugur Akkafa 72
94541771 Hakan Aktas 92
36945245 Fatih Yagci 98
【问题讨论】:
-
您的
bubble_sort函数将对int数组进行排序,但您想对struct student_grades数组进行排序。这是不可能的。您必须创建一个可以对struct student_grades数组进行排序的冒泡排序函数。请注意,交换会有点困难,因为您必须交换结构。 -
在修复此代码中的大量其他错误的同时,也可以修复此问题:
while (!feof(stu))。 -
@WhozCraig 我想你明白了。操作:
while(!feof(stu)) { fscanf(stu,"%d",&stg[i].number); ... fscanf(stu,"%d",&stg[i].grade);-->while (4 == fscanf(stu,"%d%9s%9s%d",&stg[i].number,stg[i].name,stg[i].surname,&stg[i].grade)) {
标签: c arrays sorting structure