【问题标题】:How do make the file have a name that the user inputs如何使文件具有用户输入的名称
【发布时间】:2014-04-01 16:53:17
【问题描述】:

好吧,在程序创建一个文件夹之后,我会在该文件夹中放置一个文件,但我希望该文件是用户输入的名称,所以我将如何做到这一点,因为我现在已经设置了所有它的作用是通过 Exampleuser 输入的名称创建一个文件,然后输入“/two”只是通过两个名称创建一个文件。

#include <iostream>
#include <direct.h>
#include <string>
#include <fstream>

using namespace std;

string newFolder = "Example";
string test ;
string two;


int main()
{

    _mkdir((newFolder.c_str()));

    getline(cin,test);
    two = test;


    fstream inout;
    inout.open(newFolder + two,ios::out);
    inout << " This is a test";
    inout.close();


    return 0;
}

【问题讨论】:

  • 什么是操作系统?
  • 文件夹名和文件名之间可能需要一个分隔符。例如,在 Linux 上为:new_folder + "/" + two.
  • 好的,感谢“\\”为我工作,因为我在 Windows 上

标签: c++ fstream mkdir


【解决方案1】:

旧的 c++ 标准要求您将 const char* 参数传递给 std::fstream::open() 方法。你可以写

inout.open(std::string(newFolder + "/" + two).c_str(),ios::out);

或者对于windows文件系统

inout.open(std::string(newFolder + "\\" + two).c_str(),ios::out);

【讨论】:

  • 为什么要构造一个临时字符串?只需:(newFolder + "/" + two).c_str()
  • @0x499602D2 我不知道它可以用括号 () 单独完成,THX。尽管如此,它可能会更好地了解 OP 的情况。
  • 根据我的经验,您可以在调用 Win API 时使用/(C++ 实现最终会在 Windows 上归结为),并且它接受它作为路径分隔符。不确定这是否得到普遍保证。
  • @MattMcNabb 可能取决于 WinOS 版本。我认为后者保证在那里工作。
【解决方案2】:
#include <iostream>
#include <fstream>
#include <string>
.
.
string filename;
cin >> filename;
string path; // the path to newfolder = "Example"
path += filename; //append filename to the path, which in  your case you should append "\\" between path and filename as well.

ofstream ofs(path); // create the file
.
.
ofs.close();

【讨论】:

  • 您的“答案”添加了哪些(基本)信息(仅代码答案不是这里想要的样式)?请解释您的代码更改及其与当前问题答案相比的优势。
  • 您对解决方案的解释是对的,但是我认为提出问题或需要此类解决方案的人会理解这是如何工作的!新的答案不一定要在现有帖子中添加一些内容,它可以是解决某些人可能更清楚的问题的替代方法。
  • '...它可以是另一种方式...' 当然可以,但不能仅使用代码。正如我已经提到的,添加一些解释。
  • 我认为代码很清楚,我添加了一点作为注释。
猜你喜欢
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多