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

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

4

3 回答 3

2

像这样:

#include <string>
#include <fstream>

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

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

std::ofstream fout(filename.c_str());
于 2013-06-29T10:54:57.010 回答
2

你可以试试:

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

一些有用的参考:

于 2013-06-29T10:55:07.377 回答
0

你可以试试这个。

#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;
}
于 2014-12-26T07:51:52.097 回答