Append an int to a std::string

C++Std

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

You cannot cast an int to a char* to get a string. Try this:

std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();

stringstream reference

Solution 3 - C++

I have a feeling that your ClientID is not of a string type (zero-terminated char* or std::string) but some integral type (e.g. int) so you need to convert number to the string first:

std::stringstream ss;
ss << ClientID;
query.append(ss.str());

But you can use operator+ as well (instead of append):

query += ss.str();

Solution 4 - C++

You are casting ClientID to char* causing the function to assume its a null terinated char array, which it is not.

from cplusplus.com :

> string& append ( const char * s ); Appends a copy of the string formed > by the null-terminated character sequence (C string) pointed by s. The > length of this character sequence is determined by the first ocurrence > of a null character (as determined by traits.length(s)).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHakon89View Question on Stackoverflow
Solution 1 - C++hmjdView Answer on Stackoverflow
Solution 2 - C++lukeView Answer on Stackoverflow
Solution 3 - C++Bojan KomazecView Answer on Stackoverflow
Solution 4 - C++WeaselFoxView Answer on Stackoverflow