The problem is that your lines are not lines.
You need to remember that string literals (forms "foo" not of type std::string , but const char* (in fact they are of type const char[N] , but for our purposes we can consider them pointers).
So, when you write code like this:
std::string foo = "bar" + 42
then the types are involved as follows:
std::string = const char* + int
In other words, your code adds an integer to the pointer, and then the resulting char pointer is saved as a string.
Note that adding an integer to a pointer is a simple arithmetic of pointers, so the compiler will not complain.
If we do this:
std::string foo = std::string("bar") + 42
then we create the correct line, and then try to add 42 to it. This is not defined, so we get a compiler error (which is at least better than doing it silently incorrectly).
The correct solution is to use a stream, as shown in one of the other answers:
std::ostringstream os("file"); os << x; std::string s = os.str();
source share