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 06:47

If you'd like to use + for concatenation of anything which has an output operator, you can provide a template version of operator+:

template <typename L, typename R> std::string operator+(L left, R right) {
  std::ostringstream os;
  os << left << right;
  return os.str();
}

Then you can write your concatenations in a straightforward way:

std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);    
std::cout << bar << std::endl;

Output:

the answer is 42

This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.

查看更多
查无此人
3楼-- · 2018-12-31 06:47

With the {fmt} library:

auto result = fmt::format("{}{}", name, age);

A subset of the library is proposed for standardization as P0645 Text Formatting and, if accepted, the above will become:

auto result = std::format("{}{}", name, age);

Disclaimer: I'm the author of the {fmt} library.

查看更多
呛了眼睛熬了心
4楼-- · 2018-12-31 06:50

As a Qt-related question was closed in favour of this one, here's how to do it using Qt:

QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);

The string variable now has someIntVariable's value in place of %1 and someOtherIntVariable's value at the end.

查看更多
牵手、夕阳
5楼-- · 2018-12-31 06:50

Suggesting an alternate solution for people like me who may not have access to C++ 11 and additional libraries/headers like boost. A simple conversion works like this:

Example the number is 4, to convert 3 into ascii we can simply use the code:
char a='0'+4

This will immediately store 4 as a character in a.

From here, we can simply concatenate a with the rest of the string.

查看更多
看淡一切
6楼-- · 2018-12-31 06:51
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
    stringstream s;
    s << i;
    return s.str();
}

Shamelessly stolen from http://www.research.att.com/~bs/bs_faq2.html.

查看更多
其实,你不懂
7楼-- · 2018-12-31 06:51

If you have C++11, you can use std::to_string.

Example:

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

name += std::to_string(age);

std::cout << name;

Output:

John21
查看更多
登录 后发表回答