problem description] there are n students who enter student data (including student number, name, grade) from the keyboard. When the student number is negative, it represents the end of the input. The student data is sorted from high to low, and the sorted student data is stored in the file stu-sort.txt.
[input form] enter student data from the keyboard.
[output form] outputs sorted data to the screen and the specified file.
[sample input]
1000 tss 69
101hgf 72
2 ius 60
-1
[sample output]
the contents of the screen and file are as follows:
101 hgf 72
1000 tss 69
2 ius 60
[sample description] Student data is defined as a structure, and student numbers and grades are defined as integers.
my code
< H1 > include < stdio.h > < / H1 > < H1 > include < stdlib.h > < / H1 >struct student {
int num;
char name[10];
int grade;
} stu [10];
void pai (struct student stu [], struct student temp,int n)
{
int i = 0, j = 0;
for (i = 0; i < n - 1; iPP) {
for (j = 0; j < n - 1 - i; jPP) {
if (stu[j].grade < stu[j + 1].grade) {
temp = stu[j];
stu[j] = stu[j + 1];
stu[j + 1] = temp;
}
}
}
}
void save (int n)
{
FILE *fp;
int i;
if ((fp = fopen("stu-sort.txt", "wb")) == NULL)
{
printf("ERROR\n");
return;
}
for (i = 0; i < n; iPP) {
if (fwrite(&stu[i], sizeof(struct student), 1, fp) != 1)
printf("ERROR\n");
}
fclose(fp);
}
int main ()
{
int i;
int n=0;
for (i = 0;; iPP)
{
scanf("%d", &stu[i].num);
if (stu[i].num < 0)
break;
scanf(" %s %d", stu[i].name, &stu[i].grade);
nPP;
}
struct student temp = { 0,"0",0 };
pai(stu, temp,n);
save(n);
for (i = 0; i < n; iPP) {
printf("%d %s %d\n", stu[i].num, stu[i].name, stu[i].grade);
}
system("pause");
return 0;
}
Why is my output correct? what is shown in the file is garbled? Please point out the mistake. Thank you!