【发布时间】:2016-10-23 21:44:53
【问题描述】:
我正在尝试让用户输入文件名,例如“你好”,并创建一个具有该文件名的文件,例如“Hello.txt”,文件名也写入了文件,所以内容也会是“Hello”。我一直在努力寻找解决方案,但没有运气(对不起,我是新手) 代码如下。
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
ofstream file;
string filename;
file.open("/Users/anthonykerr/Desktop");
cout << "Please enter a file name to write: ";
cin >> filename;
file << filename << endl;
file.close();
cout << filename << endl;
return 0;
【问题讨论】:
-
那么当你调用
file.open(...)时,你会打开哪个文件? -
好吧,您缺少创建该文件还是什么??
-
不要使用
file.open或file.close。根据 RAII 原则,文件将在程序结束时超出范围时关闭。只需在cin >> filename;之后使用ofstream file{"/Users/anthonykerr/Desktop/"+filename};(也将打开文件)。 -
会发生什么?什么不会发生?请描述观察到的行为。