写入.TXT文本,和依行读取.TXT输出结果

初学时的代码,一个是char型,默认输入性别是单个字符,可以通过string对象来修改。   以及没有采用嵌入类的方法写,有写臃肿,部分读写模块还是不错的

​
#include<iostream>
#include <fstream>
#include<string>
using namespace std;
struct Fishoil {   
public:
	Fishoil();
	string name;
	string number;
	char male;
	void change_name();
	void change_number();
	void change_male();
	void writein();
	void buttony_n();
	void button();
	void button1();
	void button2();
};


Fishoil::Fishoil() {
	name = "你的姓名";
	number = "号码";
	male = 'M';
}


void Fishoil::change_name() {
	string new_name;
	cout << "姓名:";
	cin >>  new_name;
	name = new_name;
}


void Fishoil::change_number() {
	string new_number;
	cout << "编号: ";
	cin >> new_number;
	number = new_number;
}


void Fishoil::change_male() {
	Fishoil fishoil;
	char new_male;
	cout << "性别: ";
	cin >> new_male;
	if (new_male != 'F' && new_male != 'M')
	{
		cout << "please try again,F means Female,M mean Male !";
		fishoil.change_male();
	}
	else 
		male = new_male;
}


void Fishoil:: writein() {   //录入数据的按钮
	ofstream myfile("fishoil.txt", ios::app);
	Fishoil fishoil;
	if (!myfile.is_open())
	{
		cout << "未成功打开文件" << endl;
	}
	myfile << fishoil.name << "  " << fishoil.number << "  " << fishoil.male<<"\n" << endl;
	myfile.close();
}


void Fishoil::buttony_n() { // 判断Y/N的按钮,
	Fishoil fishoil;
	int c1=0;
	cout << "您是否需要继续录入数据 ?[Y/N]\n";
	char yorn;
	cin >> yorn;
	if (yorn == 'Y')
	{
		fishoil.button1();
		fishoil.buttony_n(); //  递归实现再次的判断
	}
	else if (yorn == 'N')
							//预留了一个返回按钮,以后可以做成N是返回上一级菜单,
		fishoil.button();
	else
		fishoil.buttony_n();
}


void Fishoil::button() { //进行选择1~3的按键主面,和按键的选择。
	Fishoil fishoil;
	int choice;
	cout << "1. 录入信息\n" << "2. 打印已录入结果\n" << "3. 退出\n";
	cout << "Please choice which button you want !\n";
	cin >>choice;      // 判断选择的按钮
	switch (choice)
	{
	case(1):
		fishoil.button1();	//录入信息按钮
		fishoil.button();	//进入主页面选择界面
	case(2):
		fishoil.button2();  // 读取 .txt文件
		fishoil.button();	// 进入主界面选择界面
	case(3):
		break;
	default:
		cout << "choice number 1~3,if you want to quit '3' means quit .\n";
		fishoil.button();
		break;
	}
}


void Fishoil::button1() {  //录入数据按钮
	Fishoil fishoil;
	fishoil.change_name();
	fishoil.change_number();
	fishoil.change_male();
	fishoil.writein();    //进入写入信息到 .txt 文件程序
	cout << "您此次录入的信息为:\n";
	cout << fishoil.name << "  " 
		<< fishoil.number << "  "
		<< fishoil.male << "  " << endl;
	fishoil.buttony_n();   //进入是否需要继续输入的判断按钮
}


void Fishoil::button2() {    // 打印数据按钮
	ifstream in("fishoil.txt");
	string filename;
	string line;

	if (in) // 有该文件  
	{
		while (getline(in, line)) // line中不包括每行的换行符  
		{
			cout << line << endl;
		}
	}
	else // 没有该文件  
	{
		cout << "no such file" << endl;
	}
}


int main() {
	Fishoil fishoil;
	fishoil.button();  //进入主页面选择按钮
	cout << "您的操作已经结束,正在退出...\n";
	system("pause");
	return 0;
}

​

猜你喜欢

转载自blog.csdn.net/qq_38336461/article/details/81738815