Why is my line not printing?

I have a code that in its smallest full form shows a problem (being a good citizen when it comes to questions) basically boils down to the following:

#include <string> #include <iostream> int main (void) { int x = 11; std::string s = "Value was: " + x; std::cout << "[" << s << "]" << std::endl; return 0; } 

and I expect him to bring

 [Value was: 11] 

Instead, instead, I only get:

 [] 

Why? Why can't I print my line? Is the line empty? Is cout somehow broken? I've gone crazy?

+7
source share
5 answers

"Value was: " is of type const char[12] . When you add an integer to it, you are effectively referencing an element of this array. To see the effect, change x to 3 .

You will need to build std::string explicitly. Again, you cannot combine std::string and an integer. To get around this, you can write in std::ostringstream :

 #include <sstream> std::ostringstream oss; oss << "Value was: " << x; std::string result = oss.str(); 
+8
source

You cannot add a pointer to a character and such an integer (you can, but it will not do what you expect).

First you need to convert x to string. You can either do this outside of the C range using the itoa function to convert an integer to a string:

 char buf[5]; itoa(x, buf, 10); s += buf; 

Or the STD path using sstream:

 #include <sstream> std::ostringstream oss; oss << s << x; std::cout << oss.str(); 

Or directly in the cout line:

 std::cout << text << x; 
+4
source

Funny :) This is what we pay for C-compatibility and lack of inline string .

In any case, I think the most readable way to do this is:

 std::string s = "Value was: " + boost::lexical_cast<std::string>(x); 

Since the return type is lexical_cast std::string here, the correct overload + will be selected.

+4
source

C ++ does not concatenate strings using the + operator. There is also no automatic progression from data types to string.

+2
source

In C / C ++, you cannot add an integer to an array of characters using the + operator, because the char array decays to a pointer. To add int to string , use ostringstream :

 #include <iostream> #include <sstream> int main (void) { int x = 11; std::ostringstream out; out << "Value was: " << x; std::string s = out.str(); std::cout << "[" << s << "]" << std::endl; return 0; } 
+2
source

All Articles