How to form a C++ string from concatenations of string literals?
I would like concatenate string literals and ints, like this:
string message("That value should be between " + MIN_VALUE + " and " + MAX_VALUE);
But that gives me this error:
error: invalid operands of types ‘const char*’ and ‘const char [6]’ to binary ‘operator+’|
What 开发者_如何学Pythonis the correct way to do that? I could split that in 2 string declarations (each concatenating a string literal and a int), but that's ugly. I've also tried << operator.
Thanks
You should probably use stringstream for this.
#include <sstream>
std::stringstream s;
s << "This value shoud be between " << MIN_VALUE << " and " << MAX_VALUE;
message = s.str();
The c++ way to do this is to use a stringstream then you can use the << operator. It will give you a more consistent code feel
There are many ways to do this, but my favourite is:
string message(string("That value should be between ") + MIN_VALUE + " and " + MAX_VALUE);
That extra string()
around the first literal makes all the difference in the world because there is an overloaded string::operator+(const char*)
which returns a string
, and operator+
has left-to-right associativity, so the whole thing is turned into a chain of operator+
calls.
#include <sstream>
#include <string>
template <typename T>
std::string Str( const T & t ) {
std::ostringstream os;
os << t;
return os.str();
}
std::string message = "That value should be between " + Str( MIN_VALUE )
+ " and " + Str( MAX_VALUE );
You probably want to use a stringstream like this:
std::stringstream msgstream;
msgstream << "That value should be between " << MIN_VALUE << " and " << MAX_VALUE;
std::string message(msgstream.c_str());
精彩评论