连接字符串和数字

Concatenate strings and numbers

本文关键字:数字 字符串 连接      更新时间:2023-10-16

我有一个函数,它接受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,….)。