【发布时间】:2019-09-02 18:18:02
【问题描述】:
我正在尝试弄清楚如何在用户命名/定义文件后指定文件的创建位置。
我正在使用的教科书对此没有任何帮助,我尝试弄乱 .open 语句中路径的定义方式,但我认为有些事情我不知道。当我定义一个路径时,因为它用引号括起来,我认为文件名变量被视为字符串文字,最终创建一个名为“文件名”的文件,而不是用户输入的任何内容。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char response;
string filename;
ofstream fileCheck1;
ifstream fileCheck;
cout << "Create file? Y(yes) or N(no)\n";
cin >> response;
if (response == 'y' || response == 'Y')
{
cout << "Please enter file name: ";
cin >> filename;
fileCheck1.open (filename);
if (fileCheck1)
cout << "file created successfully\n";
else
cout << "error opening file\n";
}
else if (response == 'n' || response == 'N')
cout << "press enter to exit\n";
else
cout << "invalid input\n";
cin.get();
cin.get();
return 0;
}
默认情况下,文件会在 Visual Studio 的项目文件所在的位置创建。
【问题讨论】:
-
阅读“当前工作目录”以及它可能不始终是可执行文件的位置。