文件输入和输出简单示例

1.文件输入输出要包含头文件<fstream>,一般不需再加<iostream>.

2.具体实例:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
	string filename;
	cout<<"Please enter the filename:\n";
	cin>>filename;
	ofstream fout;
	fout.open(filename.c_str());
	//fout.open("fileio.txt");
	fout<<"For your eyes only\n";
	cout<<"Enter your secret number:";
	float secret;
	cin>>secret;
	fout<<"Your secret number is "<<secret<<endl;
	fout.close();
	ifstream fin(filename.c_str());
/*	fin.open(filename.c_str());*/
	cout<<"Here are the contents of "<<filename<<":\n";
	char ch;
	while(fin.get(ch))
		cout<<ch;
	cout<<"Done\n";
	fin.close();
	return 0;

}


 

3.运行结果:

程序目录中被创建了文件名为“fileio.txt"的文件,

文件输入和输出简单示例_第1张图片

 

你可能感兴趣的:(文件输入和输出简单示例)