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();
精彩评论