83

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);
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
Hakon89
  • 1,011
  • 2
  • 9
  • 17

4 Answers4

228

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));
    
hmjd
  • 120,187
  • 20
  • 207
  • 252
9

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

luke
  • 36,103
  • 8
  • 58
  • 81
4

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();
Bojan Komazec
  • 9,216
  • 2
  • 41
  • 51
2

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

WeaselFox
  • 7,220
  • 8
  • 44
  • 75