gpt4 book ai didi

c++ - 自动创建文件名 C++

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:04 25 4
gpt4 key购买 nike

我正在尝试用 C++ 编写一个程序,它会创建一些文件 (.txt) 并在其中记下结果。问题是这些文件的数量在开始时并不固定,只出现在程序结束附近。我想将这些文件命名为“file_1.txt”、“file_2.txt”、...、“file_n.txt”,其中 n 是一个整数。

我不能使用连接,因为文件名需要类型“const char*”,而且我没有找到任何方法将“string”转换为这种类型。我还没有通过 Internet 找到任何答案,如果您能帮助我,我将非常高兴。

最佳答案

您可以使用 c_strstd::string 获取 const char*成员函数。

std::string s = ...;
const char* c = s.c_str();

如果你不想使用std::string(也许你不想做内存分配)那么你可以使用snprintf创建格式化字符串:

#include <cstdio>
...
char buffer[16]; // make sure it's big enough
snprintf(buffer, sizeof(buffer), "file_%d.txt", n);

n 这里是文件名中的数字。

关于c++ - 自动创建文件名 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com