📄 gpa.cpp
字号:
//这个程序在本书所带软盘中。文件名为GPA.CPP
//这个程序利用子程序来处理学生GPA的输入、二进制文件的建立,以及读入及显示操作。
#include <fstream.h>
#include <ctype.h>
#include <conio.h>
#include <stdio.h>
struct student_strc { //定义一个结构类型
long ID_num;
char name[40];
float GPA;
} student; //定义一个结构变量student
void main(void)
{
student_strc get_data(void); //定义一个返回结构的子程序
void output(student_strc *, fstream &); //定义处理二进制文件的输出的子程序
void input(fstream &); //定义处理二进制文件的读入及显示的子程序
char choice;
fstream fname("a:\GPA.bin", ios::binary | ios::out | ios::in);
//打开并建立文件操作类型
do {
student = get_data(); //调用子程序
output(&student, fname); //调用子程序
cout << endl <<"你想继续运行程序吗? (y/n): ";
choice = getche();
cout << endl;
} while(toupper(choice) == 'Y');
input(fname); //调用子程序
fname.close(); //关闭文件
}
/********** 子程序 get_data() *******************/
student_strc get_data(void) //定义一个返回结构的子程序头
{
student_strc who; //定义一个局部结构变量
cout << "请输入学生号码: ";
cin >> who.ID_num;
cout << "请输入学生姓名: ";
gets(who.name);
cout << "请输入GPA: ";
cin >> who.GPA;
return(who);
}
/************** 子程序 output( ) ******************/
void output(student_strc *who, fstream &file)
{
file.write((char*)who, sizeof(student_strc)); //输出整个结构
}
/* ******** 子程序 input() *********************/
void input(fstream &file)
{
student_strc who; //定义一个局部结构变量
file.seekg(0L, ios::beg); //将位置指针移到文件头
while(file.peek() != EOF)
{
file.read((char*)&who, sizeof(student_strc));
//读入整个结构
cout << endl << who.ID_num;
cout << endl << who.name;
cout << endl << who.GPA << endl;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -