C++ 结构体数据写入文件

namespace _02
{
	struct student
	{
		char name[20];
		char sex[20];
		int age;
	};
	void run() 
	{
		const int num = 2;
		student stu[num];
		string path = "D://1.txt";
		fstream fout(path, ios::out|ios::app);

		if (fout.fail())
		{
			cout << "文件打开失败" << endl;
			exit(0);
		}

		for(int i = 0; i < num; i++)
		{
			cout << "姓名:";
			cin >> stu[i].name;
			cout << "性别:";
			cin >> stu[i].sex;
			cout << "年龄:";
			cin >> stu[i].age;

			fout << stu[i].name << " " << stu[i].sex << " " << stu[i].age << endl;
		}

		fout.close();
	}
}

int main()
{
	_02::run();
	return 0;
}

你可能感兴趣的:(Cpp)