Repeat after me. C++ is not Java.
Now, your problem. String literals are of type const char *. You can't
add them. Also, what you think the adding of w does is not right.
I assume you're trying to get "blah0blah". For that you should use a
stringstream.
#include <sstream>
#include <string>
int main()
{
int w = 0;
std:
streamstring ss;
ss << "blah" << w << "blah";
std::string z = ss.str();
}- Hide quoted text -
- Show quoted text -
I am not keen on the insistence that std:
stringstream is the only
valid way to convert a variable to its string representation.
ostringstream is very useful for building a sentence out of assorted
variables, but its flexibility does cost in performance. So while I do
use the 'stream solution in UI code and the like, in more performance
sensitive situations I would generally solve the original problem
using code along the lines of:
string z("blah");
char buffer[12];
z += _atol(w, buffer, 10); // convert long to C string
z += "blah";
(Where I think I'm assuming posix conformance? Is _atol more than
likely to be about?)
I would not even try to use operator+ in this situation, as it uses a
temporary to store the return value for each invocation. Whereas
operator+= simply appends the new string to the buffer of the existing
instance. But if you were determined to do it, then the following
"works".
char buffer[12];
string z = string("blah") + _ltoa(w, buffer, 10) + "blah ";
Note that I would generally wrap the _atol and buffer in a naive
little class. This class is only intended to be used with operator+=
and does will not even compile in most other situations.
class ToString
{
public:
ToString(long value)
{
_ltoa(value, buffer, radix);
}
operator const char*() const
{
return buffer;
}
private:
static const int radix = 10;
// INT_MIN (-2147483647 - 1)
// INT_MAX 2147483647
// longest string = 11 chars + 1 for null terminator
static const int bufferSize = 12;
char buffer[bufferSize];
};
Which allows you to write:
string z("blah");
z += ToString(w);
z += "blah";
The boost.lexical_cast also allows you to write code of a similar form
using boost::lexical_cast;
string z("blah");
z += lexical_cast<string>(w);
z += "blah";
but lexical_cast uses std:
streamstream to do the work so has the
same performance as the normal 'stream solution.
Andy