函数指针及从文件读取的列子

#include<stdio.h>
#include <iostream>
#include<process.h>
#include<stdlib.h>
using namespace std;
struct student
{
int i;
char sname[20];
float f;
};


struct student  array[20] = {0};


void sortbyname(student a[], int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (strcmp(a[j].sname,a[j + 1].sname)<0)
{    
char t[20];
strcpy(t, a[j].sname);
strcpy(a[j].sname, a[j + 1].sname);
strcpy(a[j + 1].sname, t);

}
}
}
for (int i = 0; i < n; i++)
{


cout << a[i].f << " " << a[i].sname << " " << a[i].i << endl;


}
}


void sortbynumb(student a[], int n)
{
int t;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (a[j].i<a[j + 1].i)
{
t = a[j].i;
a[j].i = a[j + 1].i;
a[j + 1].i = t;
}
}
}
for ( int i = 0; i < n; i++)
{


cout << a[i].f << " " << a[i].sname << " " << a[i].i << endl;


}


}


void sortbyscore(student a[], int n)
{
float t;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (a[j].f<a[j + 1].f)
{
t = a[j].f;
a[j].f = a[j + 1].f;
a[j + 1].f = t;
}
}
}
for (int i = 0; i < n; i++)
{


cout << a[i].f << " " << a[i].sname << " " << a[i].i << endl;


}
}




int main()


{



float t = 0;
FILE*fp = fopen("C:\\Users\\admin\\Desktop\\软件培训\\students.txt", "r");
if (fp == NULL)
cout << "文件打开失败 "<<endl;
else
cout << "文件打开成功 " << endl;
int j = 0;
while (!feof(fp))
{
fscanf(fp, "%d%s%f", &array[j].i, array[j].sname, &array[j].f);
++j;
}
fclose(fp);
int n = j;
cout << "请输入一个学生上的姓名"<<endl;
char s[20];
cin >> s;
for (int i = 0; i < n; i++)
{


    //cout << array[i].f <<" " <<array[i].sname <<" "<< array[i].i<<endl;
    if (strcmp(array[i].sname ,s)==0)
cout << array[i].f<<endl;
}


for (int i = 0; i < n; i++)
{
for (j = 0; j < n -i-1; j++)
{
if (array[j].f<array[j + 1].f)
{
t = array[j].f;
array[j].f = array[j + 1].f;
array[j + 1].f = t;
}
}
}
for (int i = 0; i < n; i++)
{


cout << array[i].f <<" " <<array[i].sname <<" "<< array[i].i<<endl;

}


void(*p)(student*, int);
int a;
do
{
cout << "请输入一个数";
cin >> a;

switch (a)
{
case 1:
p = &sortbyname;
p(array, n);
break;
case 2:
p = &sortbynumb;
p(array, n);
break;
case 3:
p = &sortbyscore;
p(array, n);
break;
}
} while (a!=0);
system("pause");
return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值