当前位置:编程学习 > C/C++ >>

求助C/C++语言设计

学生成绩管理。学生信息:姓名、性别、省份、电话号码。设计一个菜单程序,选择数字键1~3分别实现:输入学生信息、删除指定学生及信息和显示指定学生信息,选择数字4则回到操作系统状态。(用文件完成)
答案:#include <cstring>
#include <fstream>
#include <iostream>
using namespace std;
#define szSTR 16

struct STU {
char name[szSTR];//姓名
int gender;//性别,0-女,1-男
char province[szSTR];//省份
char phone[szSTR];//电话
};

ostream & operator < (ostream & o, STU & s)
{
o.write((char*)&s, sizeof(s));
return o;
}

ostream & operator <<(ostream & o, STU & s)
{
o << s.name << '\\t';
o << (s.gender ? "男":"女") << '\\t';
o << s.province << '\\t';
o << s.phone << endl;
return o;
}

istream & operator > (istream & i, STU & s)
{
i.read((char*)&s, sizeof(s));
return i;
}

istream & operator >>(istream & i, STU & s)
{
cout << "请输入学生姓名:";
i >> s.name ;
cout << "请输入学生性别(输入一个非零的数表示男生,零表示女生):";
i >> s.gender ;
cout << "请输入家庭省份:";
i >> s.province ;
cout << "请输易做图系电话:";
i >> s.phone ;
return i;
}

int locate(char * file, char * name, STU * s)
{
if(!file || !name) return -1;
ifstream f(file, ios_base::binary);
if(!f) return -1;
streampos p = 0;
while(!f.eof()) {
p = f.tellg();
f > *s;
if(strcmp(name, s->name )) continue;
f.close();
return (int)p;
}//end while
f.close ();
return -1;
}

void clear(char * file)
{
if(!file) return ;
STU s; char name[szSTR]="";
cout << "请输入要删除的学生姓名:";
cin >> name ;
int p = locate(file, name, &s );
if(p < 0) {
cout << "查无此人!" << endl;
return ;
}//end if
ofstream f(file, ios::binary);
f.seekp((streampos)p);
memset(&s, 0, sizeof(s));
f < s;
f.close ();
cout << "操作成功!" << endl;
}

void insert(char * file)
{
if(!file) return ;
STU s,t;
cin >> s;
int p = locate(file, s.name, &t);
if(p>-1) {
cout << "记录已存在,需要覆盖吗(y/n)?";
char c = 0;
cin >> c;
if(c != 'y' && c!= 'Y') {
cout << "操作已放弃" << endl;
return ;
}//end if
ofstream f(file, ios::binary);
f.seekp((streampos)p);
f < s;
f.close();
}else{
ofstream a(file, ios::binary|ios::app);
a < s;
a.close();
}//end if
cout << "操作成功!" << endl;
}

void query(char * file)
{
if(!file) return;
STU s; char name[szSTR] ="";
cout << "请输入要查询的学生姓名:";
cin >> name ;
int p = locate(file, name, &s);
if (p < 0)
cout << "查无此人!" << endl;
else
cout << s;
//end if
}

int main(void)
{
char file[] = "c:\\\\contact.txt";
int cmd = 0;
for(;;) {
cout << "欢迎使用学生通信簿!请选择:1-新增;2-删除;3-查询;4-返回操作系统" <<endl;
cin >> cmd;
switch(cmd) {
case 1: insert(file); break;
case 2: clear (file); break;
case 3: query (file); break;
case 4: return 0;
default: cout << "错误的选择,请重新输入!" <<endl; break;
}//end case
}
return 0;
}

上一个:谁学过C++ 指导指导
下一个:C++做五子棋的方案急

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,