How to create ofstream file with name of variable?

天涯浪子 提交于 2019-12-01 14:52:35

You could try:

#include <string>
#include <iostream>
#include <fstream>

int main() {
    // use a dynamic sized buffer, like std::string
    std::string filename;
    std::getline(std::cin, filename);
    // open file, 
    // and define the openmode to output and truncate file if it exists before
    std::ofstream fout(filename.c_str(), std::ios::out | std::ios::trunc);
    // try to write
    if (fout) fout << "Hello World!\n";
    else std::cout << "failed to open file\n";
}

Some useful references:

Like this:

#include <string>
#include <fstream>

std::string filename;
std::getline(std::cin, filename);
std::ofstream fout(filename);

In older versions of C++ the last line needs to be:

std::ofstream fout(filename.c_str());

You can try this.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string fileName;
    cout << "Give a name to your file: ";
    cin >> fileName;
    fileName += ".txt"; // important to create .txt file.
    ofstream createFile;
    createFile.open(fileName.c_str(), ios::app);
    createFile << "This will give you a new file with a name that user input." << endl;
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!