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条回答
Anthone
2楼-- · 2019-01-08 04:44
cout << text << " " << i << endl;
查看更多
成全新的幸福
3楼-- · 2019-01-08 04:45

One method here is directly printing the output if its required in your problem.

cout << text << i;

Else, one of the safest method is to use

sprintf(count, "%d", i);

And then copy it to your "text" string .

for(k = 0; *(count + k); k++)
{ 
  text += count[k]; 
} 

Thus, you have your required output string

For more info on sprintf, follow: http://www.cplusplus.com/reference/cstdio/sprintf

查看更多
beautiful°
4楼-- · 2019-01-08 04:46

These work for general strings (in case you do not want to output to file/console, but store for later use or something).

boost.lexical_cast

MyStr += boost::lexical_cast<std::string>(MyInt);

String streams

//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();

// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;
查看更多
别忘想泡老子
5楼-- · 2019-01-08 04:48

With C++11, you can write:

int i = 4;
std::string text = "Player ";
text += std::to_string(i);
查看更多
对你真心纯属浪费
6楼-- · 2019-01-08 04:48
cout << text << i;
查看更多
在下西门庆
7楼-- · 2019-01-08 04:48

You also try concatenate player's number with std::string::push_back :

Example with your code:

int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;

You will see in console:

Player 4

查看更多
登录 后发表回答