如何根据用户输入C ++创建文本文件

时间:2016-03-16 21:38:01

标签: c++

我对C ++很新。我创建了一个代码,用于输入文件并将结果输出到输出文件中,并使用堆栈和垃圾。

但我想要做的是根据用户输入创建一个文件。如果用户想要创建该空文件,则询问用户(当文件不存在于特定目录中时)。我在C#上使用目录和词典完成了这项工作,但C ++并没有真正为我点击。这是我的代码片段(我不会在一件事情上粘贴200多行)以及我想要做的事情。忽略评论。只是为了跟踪我正在做的事情。

if (file.is_open()) //if the file is open (and works)
{
string output;
cout << "Please enter the full directory of  the file you would like to have the results in" << endl;
cin >> output;
output.c_str();
file_result.open(output); //open the results file for checking answers 
while (file_result.fail())
{
cout << "This file does not exist. Would you like to make one?" << endl;
}

如您所见,我向用户询问他们是否愿意将该文件放在我希望的位置。

任何帮助都很可爱!从C#过渡到C ++是一个坏主意。

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式打开文件进行写入(附加模式):

std::ofstream ofs;
ofs.open (output.c_str(), std::ofstream::out | std::ofstream::app);
ofs << " more lorem ipsum";
ofs.close();

有关文件操作的更多信息,请访问: http://www.cplusplus.com/reference/fstream/ofstream/open/

答案 1 :(得分:1)

根据用户输入创建文件的最基本方法是这样,你应该如何包括检查以确保路径有效并且没有文件存在等等。我只有时间向你展示如何做此

#include <fstream>
#include <iostream>
#include <string>
using namespace std;


int main()
{  
  ofstream outFile;
  string path;
  cout << "Please enter the full path for your file: ";
  getline(cin, path);
  outFile.open(path);

  return 0;
}

这里发生的事情非常简单,用户输入了由getline(cin,path)读取的完整路径(C:\ Hello.txt)并存储在路径中。

然后

outfile创建该文件。

请确保添加支票以验证该名称已存在的文件等。我稍后会用更好的示例更新此内容,但这会为您创建一个文件

相关问题