题目要求
1.定义一个结构,至少存储:姓名、身份证、性别
2.实现文件存储
3.可以打印到屏幕
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
struct user
{
string username;
string userid;
string usersex;
};
int main()
{
string userdata;//作为读取中间变量
char choice;
int flag=1;
ifstream readfile;
ofstream writefile;
user newuser; //作为写入事件的中间构造体
user theone ={"小明","10086","m"};
writefile.open("E:\\user.txt");
writefile<<theone.username<<'\t'<<theone.userid<<'\t'<<theone.usersex<<'\n';
writefile.close();//文件初始化,创建txt文本方便后面搞事
for(int i=1;flag!=0;i++)
{
if(i>=2)
cout<<"还有什么要做的吗?"<<endl;
cout<<"选择需要的操作:\n"<<"1.打印数据到控制台屏幕\n"<< "2.录入新的数据\n"<<"3.退出\n";
cin>>choice;
cin.ignore(100,'\n');//吃掉回车
switch(choice)
{
case '1':
cout<<"----------------------------------------------------------------------------"<<endl;
cout<<"用户名"<<'\t'<<"序列号"<<'\t'<<"性别"<<endl;
readfile.open("E:\\user.txt");
if(readfile.is_open()==0)
{
cout<<"打开文件失败,请检查文件!"<<endl;
cout<<"----------------------------------------------------------------------------"<<endl;
cout<<"\n";
}
while(getline(readfile,userdata))
{
cout<<userdata<<endl;
}
readfile.close();
cout<<"----------------------------------------------------------------------------"<<endl;
cout<<"打印完成~"<<endl;
cout<<"\n";
break;
case '2':
cout<<"请输入用户名:\n";
getline(cin,newuser.username);
cout<<"请输入序列号:\n";
getline(cin,newuser.userid);
cout<<"请输入性别:\n";
getline(cin,newuser.usersex);
writefile.open("E:\\user.txt",ios::app);//打开输出文件流
writefile<<newuser.username<<'\t'<<newuser.userid<<'\t'<<newuser.usersex<<'\n';
cout<<"输入完了~"<<'\n';
writefile.close();
cout<<"----------------------------------------------------------------------------"<<endl;
cin.clear();
break;
case '3':
cout<<"拜拜~"<<endl;
cout<<"----------------------------------------------------------------------------"<<endl;
flag=0;
break;
default:
cout<<"输入正确指令!看不懂啊!"<<endl;
cout<<"----------------------------------------------------------------------------"<<endl;
break;
}
}
return 0;
}