gpt4 book ai didi

c++ - 将 int 附加到 std::string

转载 作者:IT老高 更新时间:2023-10-28 12:10:26 25 4
gpt4 key购买 nike

为什么这段代码会给出调试断言失败?

   std::string query;
int ClientID = 666;
query = "select logged from login where id = ";
query.append((char *)ClientID);

最佳答案

std::string::append()方法期望它的参数是一个以 NULL 结尾的字符串 (char*)。

有几种方法可以生成包含 intstring:

  • std::ostringstream

    #include <sstream>

    std::ostringstream s;
    s << "select logged from login where id = " << ClientID;
    std::string query(s.str());
  • std::to_string (C++11)

    std::string query("select logged from login where id = " +
    std::to_string(ClientID));
  • boost::lexical_cast

    #include <boost/lexical_cast.hpp>

    std::string query("select logged from login where id = " +
    boost::lexical_cast<std::string>(ClientID));

关于c++ - 将 int 附加到 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10516196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com