连接字符串和数字
Concatenate strings and numbers
我有一个函数,它接受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::ostringstream os;
os << "file" << fileID << ".xml";
open(os.str().c_str());
您可以使用前面所述的stringstream
或Boost格式:
#include <boost/format.hpp>
void loadFile(int fileID)
{
std::string filename = (boost::format("File%d.xml") % fileID).str();
open(filename.c_str();
}
如果您的编译器支持C++11,您可以使用std::to_string来获得数字的字符串表示:
std::string filename = "file" + std::to_string(fileId) + ".xml";
然而,如果您有Boost可用,我认为使用Boost格式(如Johan的回答中所讨论的)更具可读性。
使用to_string()
open("file" + to_string(fileID) + ".xml");
C++是C的超集。您可以使用sprintf:
void loadFile(unsigned int fileID)
{
const int BUFFER_SIZE = 128;
char buffer[BUFFER_SIZE];
sprintf(buffer,"file%u.xml");
open(buffer);
}
这是可移植的,应该对所有传入(uint)值等都是安全的。
如果您担心溢出缓冲区,也可以使用snprintf(buffer,buffer_SIZE,….)。
相关文章:
- 生成随机长度的数字字符串
- 如何在c ++中将大数字字符串转换为整数?
- 将非数字字符串存储为二进制整数
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- 如何在C++中将数字字符串拆分为数组
- 总结数字字符串输入的最佳方法
- 如何将输入的数字字符串转换为 int 数组
- 如何获得两个数字字符串的总和-C
- 使用 C++ 替换 txt 文件中的文本数字字符串
- 如何有效地将数字字符串值分配给整数
- String Stream in C++ 解析单词和数字字符串
- c++将大型数字字符串映射到数字字符串范围
- 获取用数字字符串表示的树中的所有直接父级/子级
- 如何从 char 数组中提取数字字符串成员
- 比较两个字母数字字符串
- 有没有一种方法可以设置浮点变量=某个数字*字符串中的变量
- 使用矢量对字母数字字符串进行排序
- 正在分析未知类型的数字字符串
- 如何在c++中从一个科学数字字符串中修剪后面的零
- 无法将字符串数组中的数字字符串转换为浮点值