Tat*_*ana 5 c++ const-char file names
我正在尝试用C++编写一个程序,它创建一些文件(.txt)并将结果写入其中.问题是这些文件的数量在开始时没有固定,只出现在程序结束附近.我想将这些文件命名为"file_1.txt","file_2.txt",...,"file_n.txt",其中n是整数.
我不能使用连接,因为文件名需要类型"const char*",我没有找到任何方法将"字符串"转换为此类型.我没有通过互联网找到任何答案,如果你帮助我,我会非常高兴.
您可以使用成员函数const char*从a获取.std::stringc_str
std::string s = ...;
const char* c = s.c_str();
Run Code Online (Sandbox Code Playgroud)
如果您不想使用std::string(可能您不想进行内存分配),那么您可以使用snprintf创建格式化字符串:
#include <cstdio>
...
char buffer[16]; // make sure it's big enough
snprintf(buffer, sizeof(buffer), "file_%d.txt", n);
Run Code Online (Sandbox Code Playgroud)
n 这是文件名中的数字.
for(int i=0; i!=n; ++i) {
//create name
std::string name="file_" + std::to_string(i) + ".txt"; // C++11 for std::to_string
//create file
std::ofstream file(name);
//if not C++11 then std::ostream file(name.c_str());
//then do with file
}
Run Code Online (Sandbox Code Playgroud)