【发布时间】:2013-11-30 21:37:06
【问题描述】:
我有一个带有const char* 参数的函数。我需要连接两个字符串文字和一个 int 以传递给这个参数。基本上这就是我想要做的:
open(const char* filename) {}
void loadFile(int fileID)
{
open("file" + fileID + ".xml");
}
int main()
{
loadFile(1);
return 0;
}
我怎样才能使这项工作尽可能简单?我尝试更改 loadFile 函数以获取 const char* 然后执行 open(std::string("file").c_str() + fileID + std::string(".xml").c_str()); 但后来我得到 error: invalid operands of types 'const char*' and 'const char*' to binary 'operator+' 所以我很迷茫。
【问题讨论】:
-
你问的越简单越好吗?使用
std::string。 -
在
int上使用std::to_string,然后在最后使用c_str。 -
@chris 如果不使用流、格式化程序或类似的东西,您将无法从
int创建string... 直接创建将失败,并且串联会将int解释为 @ 987654335@. -
@Johan,
std::to_string将其转换为字符串。 -
@chris:我相信这是一个 C++11 函数。
标签: c++ concatenation