开发者

combine a char and an int to a string

开发者 https://www.devze.com 2023-02-28 15:11 出处:网络
For example; int i = 1; ch开发者_开发知识库ar c = \'V\'; string s; Result: s = \"1 V\" Can anybody tell me how to do that?

For example;

int i = 1;
ch开发者_开发知识库ar 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();
0

精彩评论

暂无评论...
验证码 换一张
取 消