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);
To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.
If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.
To convert from string representation to integer value, we can use std::stringstream. if the value converted is out of range for integer data type, it returns INT_MIN or INT_MAX. Also if the string value can't be represented as an valid int data type, then 0 is returned.
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));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With