How to concatenate a string and an int in C++

Methods

  • Use std::stringstream
  • Use boost::lexical_cast()
  • Use boost::format()
  • Use std::to_string() (C++11)

Method 1. Use std::stringstream

#include <sstream>

std::stringstream ss;
ss << name << age;
result = ss.str();

Method 2. Use boost::lexical_cast()

#include <boost/lexical_cast.hpp>

result = name + boost::lexical_cast<std::string>(age);

Reference: Boost.Lexical_Cast

Method 3. Use boost::format()

#include <boost/format.hpp>

result =  boost::str(boost::format("%s%d") % name % age);

Reference: Boost Format library

Method 4. Use std::to_string() (C++11)

result = name + std::to_string(age);

Method 5. Use folly::toAppend()

#include <folly/Conv.h>

result =  name;
folly::toAppend(age, &result);

Reference: folly/Conv.h

Related