Append an int to a std::string

Hakon89 picture Hakon89 · May 9, 2012 · Viewed 167.1k times · Source

Why is this code gives an Debug Assertion Fail?

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

Answer

hmjd picture hmjd · May 9, 2012

The std::string::append() method expects its argument to be a NULL terminated string (char*).

There are several approaches for producing a string containg an int:

  • 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));