【c++】 复杂数据类型对象的基础:结构

题目要求
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值