#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)
本文详细解读了一段C++代码的功能,包括文件创建、内容写入和读取。代码通过`ofstream`和`ifstream`实现文件操作,并通过控制台交互获取用户输入的数据。该代码展示了C++中文件I/O的基本应用。
1439

被折叠的 条评论
为什么被折叠?



