How to concatenate a std::string and an int?

2018-12-31 06:29发布

I thought this would be really simple but it's presenting some difficulties. If I have

std::string name = "John";
int age = 21;

How do I combine them to get a single string "John21"?

29条回答
倾城一夜雪
2楼-- · 2018-12-31 07:07

You can concatenate int to string by using the given below simple trick, but note that this only works when integer is of single digit. Otherwise, add integer digit by digit to that string.

string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;

Output:  John5
查看更多
初与友歌
3楼-- · 2018-12-31 07:08

The detailed answer is buried in below other answers, resurfacing part of it:

#include <iostream> // cout
#include <string> // string, to_string(some_number_here)

using namespace std;

int main() {
    // using constants
    cout << "John" + std::to_string(21) << endl;
    // output is:
    //    John21

    // using variables
    string name = "John";
    int age = 21;
    cout << name + to_string(age) << endl;
    // output is:
    //    John21
}
查看更多
流年柔荑漫光年
4楼-- · 2018-12-31 07:10
  • std::ostringstream
#include <sstream>

std::ostringstream s;
s << "John " << age;
std::string query(s.str());
  • std::to_string (C++11)
std::string query("John " + std::to_string(age));
  • boost::lexical_cast
#include <boost/lexical_cast.hpp>

std::string query("John " + boost::lexical_cast<std::string>(age));
查看更多
低头抚发
5楼-- · 2018-12-31 07:12

This is the easiest way:

string s = name + std::to_string(age);
查看更多
牵手、夕阳
6楼-- · 2018-12-31 07:12

There are more options possible to use to concatenate integer (or other numerric object) with string. It is Boost.Format

#include <boost/format.hpp>
#include <string>
int main()
{
    using boost::format;

    int age = 22;
    std::string str_age = str(format("age is %1%") % age);
}

and Karma from Boost.Spirit (v2)

#include <boost/spirit/include/karma.hpp>
#include <iterator>
#include <string>
int main()
{
    using namespace boost::spirit;

    int age = 22;
    std::string str_age("age is ");
    std::back_insert_iterator<std::string> sink(str_age);
    karma::generate(sink, int_, age);

    return 0;
}

Boost.Spirit Karma claims to be one of the fastest option for integer to string conversion.

查看更多
登录 后发表回答