Home > Backend Development > C++ > body text

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

Patricia Arquette
Release: 2024-11-10 14:47:02
Original
890 people have browsed it

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);
Copy after login

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());
Copy after login
  1. std::to_string (C 11 and later):
std::string query("select logged from login where id = " +
                  std::to_string(ClientID));
Copy after login
  1. boost::lexical_cast:
#include <boost/lexical_cast.hpp>

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template