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