将整数连接到const char *字符串 [英] Concatenating integers to const char* strings
问题描述
我有几个这样命名的文件: file1
, file2
, file3
等。
I have a few files named like so: file1
, file2
, file3
, etc.
我有一个函数:
load(const char *file)
我称之为 load(file1)
, load(file2)
等。
我是尝试根据导入的文件数更动态地执行此操作。
I am trying do this a bit more dynamically, based on the number of files imported.
因此,如果我有多个文件,请执行以下操作:
So if I have more than 1 file do something like this:
if (NUM_OF_FILES > 1) {
for (int i = 2; i <= NUM_OF_FILES; i++) {
load("file" + i);
}
}
但是,这不起作用。
有办法吗?
推荐答案
字符串文字的类型像文件
是 char const [N]
(带有合适的 N
)在第一次获得机会时愉快地腐化为 char const *
。尽管在 T [N]
和 int
之间没有伪造的附加项,但在<$ c $之间定义了附加项c> char const * 和 int
:它将 int
添加到指针。
The type of a string literal like "file"
is char const[N]
(with a suitable N
) whic happily decays into a char const*
upon the first chance it gets. Although there is no addition defeined between T[N]
and int
, there is an addition defined between char const*
and int
: it adds the int
to the pointer. That isn't quite what you want.
您可能想将 int
转换为合适的 std :: string
,将其与您获得的字符串文字结合起来,并从中获得 char const *
:
You probably want to convert the int
into a suitable std::string
, combine this with the string literal you got, and get a char const*
from that:
load(("file" + std::to_string(i)).c_str());
这篇关于将整数连接到const char *字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!