【问题标题】:Concatenate strings and numbers [duplicate]连接字符串和数字[重复]
【发布时间】: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


【解决方案1】:

你需要使用类似的东西:

std::ostringstream os;
os << "file" << fileID << ".xml";
open(os.str().c_str());

【讨论】:

    【解决方案2】:

    您可以使用前面所述的stringstreamBoost format

    #include <boost/format.hpp>
    
    void loadFile(int fileID)
    {
      std::string filename = (boost::format("File%d.xml") % fileID).str();
      open(filename.c_str();
    }
    

    【讨论】:

    • 通过format 函数的相关包含和完全限定访问会更完整。
    • @CaptainObvlious 完成!
    【解决方案3】:

    如果你的编译器支持 C++11,你可以使用std::to_string 来获取数字的字符串表示:

    std::string filename = "file" + std::to_string(fileId) + ".xml";
    

    但是,如果您有可用的 Boost,我认为使用 Boost 格式(如 Johan 的回答中所讨论的)更具可读性。

    【讨论】:

    • 之所以选择是因为我可以将所有内容都保留在函数调用中,open(std::string("file" + std::to_string(fileID) + ".xml").c_str()); 这正是我的目标。
    【解决方案4】:

    使用 to_string()

    open("file" + to_string(fileID) + ".xml");
    

    【讨论】:

      【解决方案5】:

      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,....)。

      【讨论】: