* mlt:
In java an int can be included in a string like:
String str = ""+33 + "strings";
In c++ I have only found:
std::string str = "test";
std::stringstream out;
out << 222;
str = str + out.str();
Is that really the only way to do this in C++?
No, there are umpteen ways, but the core language and standard library does not
support the simple Java syntax.
In C++ you decide what libraries to use, or you create the functionality.
E.g., check out boost::lexical_cast, from the Boost library.
Or if installing Boost sounds daunting (note: you don't have to build anything
to use simple functionality like lexical_cast), you can create such
functionality yourself by -- yes -- writing appropriate small routines
and/or classes.
And that is probably best, because for reasons of efficiency you really
shouldn't use string value concatenation as the default. For almost no matter
the language it leads easily to O(n^2) behavior in loops, that is, time that
increases as the square of the number of items, which goes slow very fast.
Instead preferentially concatenate on to the end of a string variable, like
<code>
#include <iostream>
#include <string>
#include <sstream>
//--------------------------------- Machinery:
std::string stringFrom( int x )
{
std:
stringstream stream;
stream << x;
return stream.str();
}
class S
{
private:
std::string myString;
public:
operator std::string& () { return myString; }
operator std::string const& () const { return myString; }
};
std::string& operator<<( std::string& s, char const rhs[] )
{
return s.append( rhs );
}
std::string& operator<<( std::string& s, int rhs )
{
return s.append( stringFrom( rhs ) );
}
//--------------------------------- Example usage:
void foo( std::string const& s )
{
std::cout << s << std::endl;
}
int main()
{
// Java: foo( "Level " + 42 + "." )
foo( S() << "Level " << 42 << "." );
}
</code>
For reuse, add "inline" to each routine definition and place the machinery in a
header file, which you can then just #include.
Hrmf, this should really be a FAQ.
Cheers & hth.,
- Alf