如何连接 std: : string 和 int?

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"?

转载于:https://stackoverflow.com/questions/191757/how-to-concatenate-a-stdstring-and-an-int

csdnceshi61
derek5. Let me add to this: I tried 'str = "hi"; str += 5; cout << str;' and saw no effect. Turns out this calls operator+=(char) and adds a non-printable character.
接近 6 年之前 回复

29个回答

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.

csdnceshi70
笑故挽风 QString("Something ") + QString::number(someIntVariable) also works
接近 3 年之前 回复

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
}

It seems to me that the simplest answer is to use the sprintf function:

sprintf(outString,"%s%d",name,age);
csdnceshi72
谁还没个明天 sprintf(char*, const char*, ...) will fail on some versions of compilers when you pass a std::string to %s. Not all, though (it's undefined behavior) and it may depend on string length (SSO). Please use .c_str()
接近 12 年之前 回复
csdnceshi61
derek5. snprintf can be tricky (mainly because it can potentially not include the null character in certain situations), but I prefer that to avoid sprintf buffer overflows potential problems.
接近 12 年之前 回复

Common Answer: itoa()

This is bad. itoa is non-standard, as pointed out here.

csdnceshi56
lrony* iota != itoa
接近 5 年之前 回复
csdnceshi54
hurriedly% iota is in the numeric header as of C++11.
8 年多之前 回复
weixin_41568208
北城已荒凉 itoa is non standard: stackoverflow.com/questions/190229/…
接近 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.

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.

  • 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));

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.

I am a beginner C++ user and found this the easiest way:

cout << name << age; 

This will successfully concatenate name and age, the the output will be "John21."

However there has to be a reason nobody said this; I think there may be a flaw in it although I haven't experienced any so far.

EDIT: I have realized that this is not necessarily the right answer, however I will keep it here in case any C++ beginners would like to know how to output concatenated strings.

csdnceshi74
7*4 However, we already have that in the other answers.
3 年多之前 回复
csdnceshi75
衫裤跑路 This could be easily converted to a good answer to the OP's question if you invoked stringstreams....
接近 5 年之前 回复
csdnceshi68
local-host Ah, I didn't interpret OP's question correctly, in that case. But IOStream would work, correct?
接近 6 年之前 回复
csdnceshi53
Lotus@ This is just output two strings together, not building up a new string. So for example you cannot pass the result to another functions. This is not an answer.
接近 6 年之前 回复
共29条数据 首页 1 3
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问