How to create ofstream file with name of variable?

后端 未结 3 1956
甜味超标
甜味超标 2021-01-17 06:08
char NAME[256];
cin.getline (NAME,256);
ofstream fout(\"NAME.txt\"); //NAME???????

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

相关标签:
3条回答
  • 2021-01-17 06:43

    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());
    
    0 讨论(0)
  • 2021-01-17 06:48

    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:

    • http://en.cppreference.com/w/cpp/string/basic_string
    • http://en.cppreference.com/w/cpp/string/basic_string/getline
    • http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream
    • http://en.cppreference.com/w/cpp/io/basic_filebuf/open
    • http://en.cppreference.com/w/cpp/io/ios_base/openmode
    0 讨论(0)
  • 2021-01-17 07:03

    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;
    }
    
    0 讨论(0)
提交回复
热议问题