+6

About cout

Cout<< 1+"hello"; Why the output is "ello"? Cout<<2+ "hello"; Why the output is "llo"? Why do we see only the pieces of the word "hello"? What does cout return with numbers?

2/9/2019 4:52:51 PM

Белка

7 Answers

New Answer

+8

Strings are arrays of characters. And arrays are implemented with pointers. Which means that what you do here is add 1 or 2 to the address of the array, and since sizeof(char) is 1, you will skip as many characters.

+4

Additionally, this approach will not work if you use it directly on a std::string object, because it is more than a simple char array. However, the same effect is possible through the use of the `c_str` or `data` member of the std::string object, which exposes the internal buffer content.

+4

~ swim ~ That's right 👍 But we can't do that on the string object, only with the .c_str or .data which exposes the internal buffer : )

+4

Though I could've been more clear if I said "this will not work if you use a std::string object directly, ..." I will make adjustment on my first post, Thanks ~ swim ~ for the note 😁

+2

If you added the 1+ at the beginning or end of the string (ex. cout << 1+"hello"), it returns "ello" because the 1+ removes a letter from the beginning of the string. The second experiment you made has removed 2 letters from the beginning of the string. So, the output will be a whole string, but a number of characters at the beginning of the string will be removed.

+2

Ipang You can do this string instr{"hello"}; cout << 1 + instr.c_str(); cout << 2 + instr.data();

+2

Ipang Internal data is a part of string object and c_str() and data methods are provided for the very same purpose, but yes i agree with what you say :)