自动创建文件名C ++ [英] Creating file names automatically C++

查看:139
本文介绍了自动创建文件名C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a program in C++, which creates some files (.txt) and writes down the result in them. The problem is that an amount of these files is not fixed at the beginning and only appears near the end of the program. I would like to name these files as "file_1.txt", "file_2.txt", ..., "file_n.txt", where n is an integer.

我不能使用连接,因为文件名需要类型const char *,我没有找到任何方法将字符串转换为这种类型。

I can't use concatenation because the file name requires type "const char*", and I didn't find any way to convert "string" to this type. I haven't found any answer through the Internet and shall be really happy if you help me.

推荐答案

你可以得到一个<使用 std :: string 中创建code> code> com / reference / string / string / c_str /rel =nofollow> c_str 成员函数。

You can get a const char* from an std::string by using the c_str member function.

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

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

If you don't want to use std::string (maybe you don't want to do memory allocations) then you can use snprintf to create a formatted string:

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

n

这篇关于自动创建文件名C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆