Home  >  Article  >  Backend Development  >  How to Append an Integer to a std::string in C ?

How to Append an Integer to a std::string in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 14:47:02910browse

How to Append an Integer to a std::string in C  ?

Appending an Integer to a std::string

The code below attempts to append an integer to a std::string using the append() method:

std::string query;
int ClientID = 666;
query = "select logged from login where id = ";
query.append((char *)ClientID);

However, this code will result in a Debug Assertion Failure. This is because the append() method expects its argument to be a NULL-terminated string (char*).

There are several approaches to append an integer to a std::string:

  1. std::ostringstream:
std::ostringstream s;
s << "select logged from login where id = " << ClientID;
std::string query(s.str());
  1. std::to_string (C 11 and later):
std::string query("select logged from login where id = " +
                  std::to_string(ClientID));
  1. boost::lexical_cast:
#include <boost/lexical_cast.hpp>

std::string query("select logged from login where id = " +
                  boost::lexical_cast<std::string>(ClientID));

The above is the detailed content of How to Append an Integer to a std::string in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn