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 04:34
cout << text << i;

The << operator for ostream returns a reference to the ostream, so you can just keep chaining the << operations. That is, the above is basically the same as:

cout << text;
cout << i;
查看更多
放荡不羁爱自由
3楼-- · 2019-01-08 04:38

For the record, you could also use Qt's QString class:

#include <QtCore/QString>

int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData();  // prints "Player 4"
查看更多
劫难
4楼-- · 2019-01-08 04:39

The easiest way I could figure this out is the following..
It will work as a single string and string array. I am considering a string array, as it is complicated (little bit same will be followed with string). I create a array of names and append some integer and char with it to show how easy it is to append some int and chars to string, hope it helps. length is just to measure the size of array. If you are familiar with programming then size_t is a unsigned int

#include<iostream>
    #include<string>
    using namespace std;
    int main() {

        string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array
        int length = sizeof(names) / sizeof(names[0]); //give you size of array
        int id;
        string append[7];    //as length is 7 just for sake of storing and printing output 
        for (size_t i = 0; i < length; i++) {
            id = rand() % 20000 + 2;
            append[i] = names[i] + to_string(id);
        }
        for (size_t i = 0; i < length; i++) {
            cout << append[i] << endl;
        }


}
查看更多
何必那么认真
5楼-- · 2019-01-08 04:39

If using Windows/MFC, and need the string for more than immediate output try:

int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);
查看更多
别忘想泡老子
6楼-- · 2019-01-08 04:40

You can use the following

int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);
查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-08 04:44

Here a small working conversion/appending example, with some code I needed before.

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}

the output will be:

/dev/video
/dev/video456
/dev/video321
/dev/video123

Note that in the last two lines you save the modified string before it's actually printed out, and you could use it later if needed.

查看更多
登录 后发表回答