简体   繁体   中英

combine a char and an int to a string

For example;

int i = 1;
char c = 'V';
string s;

Result:

s = "1 V"

Can anybody tell me how to do that? Thank you

Use std::stringstream from <sstream> header file, as:

#include <sstream>

int i = 1;
char c = 'V';

std::stringstream ss;
ss << i << " " << c;
std::string s = ss.str();
std::cout << s;

Output:

1 V

I've implemented stringbuilder using which you can do this just in one line:

std::string s = stringbuilder() << i << " " << c;

Here is the implementation of stringbuilder :

struct stringbuilder
{
   std::stringstream ss;
   template<typename T>
   stringbuilder & operator << (const T &data)
   {
        ss << data;
        return *this;
   }
   operator std::string() { return ss.str(); }
};
stringstream str;

str<<< i << c;

string s=str.str();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM