C++文件和流

#include <fstream>
#include <iostream>
using namespace std;

int main()
{
	char data[100];
	//以写模式打开
	ofstream outfile;
	outfile.open("afile.bat");
	cout << "Writing the file" << endl;
	cout << "Enter you name" << endl;
	cin.getline(data, 100);

	// 向文件写入用户输入的数据
	outfile << data << endl;

	cout << "Enter you age" << endl;
	cin >> data;
	cin.ignore();


	// 再次向文件写入用户输入的数据
	outfile << data << endl;
	// 关闭打开的文件
	outfile.close();

	// 以读模式打开文件
	ifstream infile;
	infile.open("afile.dat");

	cout << "Reading from the file" << endl;
	
	// 再次从文件读取数据并显示
	infile >> data;
	cout << data << endl;
	infile.close();

	system("pause");
	return 0;

}

猜你喜欢

转载自blog.csdn.net/qq2942713658/article/details/81805114