【问题标题】:I'm trying to make a small program where the user enters a filename, and the name of the file is written into the txt file我正在尝试制作一个用户输入文件名的小程序,并将文件名写入txt文件
【发布时间】: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.openfile.close。根据 RAII 原则,文件将在程序结束时超出范围时关闭。只需在cin &gt;&gt; filename; 之后使用ofstream file{"/Users/anthonykerr/Desktop/"+filename};(也将打开文件)。
  • 会发生什么?什么不会发生?请描述观察到的行为。

标签: c++ string file filenames


【解决方案1】:

考虑使用freopen。它将流重定向到文件。

#include <iostream>
#include <cstdio>
#include <string>

int main()
{
    std::string filename;
    std::cin >> filename;

    //using freopen: 
    //              filename.c_str() is filename converted to char sequnce
    //              "w" means, that the file is opened in "write" mode
    //              stdout is the stream redirected to file
    std::freopen(filename.c_str(), "w", stdout);

    //cout was redirected to file, so filename is written in the file
    std::cout << filename;
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多