#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string filename;
cout<<"Enter name for new file: ";
cin>>filename;
ofstream fout(filename.c_str());
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());
cout<<"Here are the contents of "<<filename<<"\n";
char ch;
while(fin.get(ch))
cout<<ch;
cout<<"Done\n";
fin.close();
return 0;
}
这段代码中,不明白c_str的意思,后来再网络上查找,原来是这样解释的:如果一个文件名被申明为“string”,那么就必须使用 “c_str”,然而,当你申明一个文件名为字符数组型,就没有必要使用,比如。
char filename[20];
in.open(finename)
otherwise
string filename;
in.open(filename.c_str)