How do you append an int to a string in C++? [dupl

2019-01-08 04:12发布

This question already has an answer here:

int i = 4;
string text = "Player ";
cout << (text + i);

I'd like it to print Player 4.

The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes?

20条回答
2楼-- · 2019-01-08 05:00

Well, if you use cout you can just write the integer directly to it, as in

std::cout << text << i;

The C++ way of converting all kinds of objects to strings is through string streams. If you don't have one handy, just create one.

#include <sstream>

std::ostringstream oss;
oss << text << i;
std::cout << oss.str();

Alternatively, you can just convert the integer and append it to the string.

oss << i;
text += oss.str();

Finally, the Boost libraries provide boost::lexical_cast, which wraps around the stringstream conversion with a syntax like the built-in type casts.

#include <boost/lexical_cast.hpp>

text += boost::lexical_cast<std::string>(i);

This also works the other way around, i.e. to parse strings.

查看更多
该账号已被封号
3楼-- · 2019-01-08 05:01
cout << text << " " << i << endl;
查看更多
登录 后发表回答