C++ 如何使用变量名创建ofstream文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17379390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:09:08  来源:igfitidea点击:

How to create ofstream file with name of variable?

c++fstreamofstream

提问by user2531700

char NAME[256];
cin.getline (NAME,256);
ofstream fout("NAME.txt"); //NAME???????

What i need to do to create file with NAME name?

我需要做什么来创建具有 NAME 名称的文件?

回答by Kerrek SB

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:

在旧版本的 C++ 中,最后一行需要是:

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

回答by moooeeeep

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:

一些有用的参考资料:

回答by Nawa

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;
}