TLD
TLD

Reputation: 8135

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

Upvotes: 0

Views: 3428

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361762

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(); }
};

Upvotes: 8

tonyhuangfu
tonyhuangfu

Reputation: 19

stringstream str;

str<<< i << c;

string s=str.str();

Upvotes: 1

Related Questions