86

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);
2
  • can you add to definition of ClientID ? is it a std::string or a char * ? Commented May 9, 2012 at 12:37
  • says invalid null-pointer by the way Commented May 9, 2012 at 12:39

4 Answers 4

234

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));
    
Sign up to request clarification or add additional context in comments.

11 Comments

+1 for boost::lexical_cast.
+1 for std::to_string
+1 for clear, clean and complete answer
std::to_string has no function that requiers an int...
It does according to the standard (check the reference link). Your compiler may not implement it yet, however.
|
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

2 Comments

Wow... its first time i see istringstream... thanks.
Sorry, that should be ostringstream. Fixed.
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();

Comments

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

2 Comments

Ok, i got it. Well how can append to the end an integer value?
see @hmjd answer down below.. he already covers this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.