Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append an int to a std::string [duplicate]

Tags:

c++

std

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); 
like image 982
Hakon89 Avatar asked May 09 '12 12:05

Hakon89


People also ask

How do you add an int to a string?

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.

Is it possible to append an integer value with string value?

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.

How do I cast a Std string to int?

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.


2 Answers

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)); 
like image 156
hmjd Avatar answered Sep 25 '22 03:09

hmjd


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

like image 38
luke Avatar answered Sep 21 '22 03:09

luke