69,371
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct Person
{
char name[20];
int age;
};
//将读到的一行字符串分离成两部分,并存放到结构体中
void fun(const char* str, struct Person* student)
{
int i =0 ;
for(i=0; str[i] != ' '; ++i)
{
student->name[i] = str[i];
}
student->name[i] = '\0';
while( ' ' == str[i] ) ++i; //去除多余的空格符
student->age = atoi(str+i);
}
//对结构体进行排序
void my_sort(struct Person* students, int start, int end)
{
if( start >= end )
{
return ;
}
int i, j;
struct Person per;
per = students[start];
i = start;
j = end;
while( i < j )
{
while( (i<j) && (students[j].age>=per.age) ) --j;
students[i] = students[j];
while( (i<j) && (students[i].age<=per.age) ) ++i;
students[j] = students[i];
}
students[i] = per;
my_sort(students, start, i-1);
my_sort(students, i+1, end);
}
void main()
{
FILE *fread = NULL, *fwrite = NULL;
fread = fopen("D:\\in.txt", "r");
fwrite = fopen("D:\\out.txt", "w");
if( (NULL == fread) || (NULL == fwrite) )
{
printf("打开文件失败\n");
return ;
}
struct Person students[5];
char str[30]; //用来存放读取的一行数据
int i = 0;
while( fgets(str, 30, fread) )
{
if( '\n' == str[0] ) //读到的是一个空行
continue;
fun(str, &students[i++]);
}
my_sort(students, 0, 4);
for(i=0; i < 5; ++i)
{
sprintf(str, "%s %d\n", students[i].name, students[i].age);
fputs(str, fwrite);
}
}
struct Stu{
char Name[32];
int age;
};