c++ - 如何使用变量作为文件名?

标签 c++

我一直在开发一个创建信息并将其存储到文件中的程序。唯一让我无法继续前进的问题是文件名。我可以手动命名文件,但我不能为文件名和文件内容使用变量(任何变量都可以:数字、字符任何东西)。下面是让我困惑了一段时间的 4 行代码:

ofstream file;
file.open ("txt.txt"); \\I can manually create names, but that's not what I'm after
file.write >> fill; \\I attempted to use a 'char' for this but it gives errors based on the "<<"
file.close(); 

这是我第一次使用这个网站。提前抱歉。

最佳答案

您可以使用字符串类型的变量,并要求用户通过键盘输入来命名您的文件并填写内容。

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char** argv) {

    string fileName;
    string contents;

    cout << "What would you like the file name be? : ";
    cin >> fileName;

    cout << "\nPlease write the contents of the file: ";
    cin >> contents;

    ofstream file;
    file.open(fileName.c_str());        // provide the string input as the file name
    if(file.is_open()){ // always check if the program sucessfully opened the file
        file << contents << endl; // write the contents into the file
        file.close();   // always close the file!
    }

    return 0;
}

请注意,此程序将读取用户输入的内容,直到遇到换行符 '\n' 或空格 ' '。因此,如果您编写 HELLO WORLD! 作为内容的输入,它只会读取 HELLO

我将把如何阅读包括空格在内的整行作为练习留给你。我还建议你拿一本 C++ 书来研究文件输入/输出。

关于c++ - 如何使用变量作为文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23555753/

相关文章:

c++ - Kinect + Visual Studio 2013 LNK 错误,如何正确链接库?

c++ - 如何制作一个数组,其中的每个数字都存储一个字符串,就像 const char * argv[ ] 那样?

c++ - 我可以使用 Excel::_Application::Run 调用 C# dll 方法吗

c++ - 在 .qrc 中添加 pdf 作为资源

python - 如何通过 ctypes 将列表列表从 Python 传递(非空)到 C++?

c++ - 绘图 "higher-level"对象

c++ - R: 安装feather包时编译报错 "ISO C++ forbids in-class initialization of non-const static member"

c++ - Makefile 报告 `func[abi:cxx11]()' 的多个定义

java - 与多个监听器的简单进程间通信

c++ - longjmp的问题