0

i was learning C++ after 6-7 years of java and i have encouter a problem, in this snippet that instead of "concat" it's just remove the n character as the input has been given..

#include <iostream>
int main()
{
    int id;
    std::cin >> id;
    std::cout << "Hello world!" + id << std::endl;
    return 0;
}

the output isn't

Hello world!*input*

but instead it's subtract to "hello world" the n character given in the input. if i give 8 the output will be rld!. If someone could explain this.. i will glad to hear! =)

Andrea Bori
  • 190
  • 2
  • 15

3 Answers3

6

This is how pointer arithmetics work in C/C++.

Basically, "Hello world!" is just a const char* and its + operator works on it like a pointer. Which means that, for example, if you add 3 to it, then instead of pointing to the beginning of "Hello world" it will point to 3 characters after the beginning. If you print that, you get llo world.
So you're not doing a string concatenation there.

If you just want to print the stuff, you can use operator << and do something like this instead:

std::cout << "Hello world!" << id << std::endl;

If you need a string that actually works like a string, consider using std::string from the standard library or if you use something like Qt, you can use QString.

With a modern compiler (that supports C++11), you can use std::to_string to create a string from an int, and then you can do it like this:

std::string s = "Hello world!";
int i;
std::cin >> i;
s += std::to_string(i);
std::cout << s;

If you consider getting seriously into C++ app development, consider using a library like Qt or boost, which make your work just that much easier, although knowing the standard library well is also a good thing. :)

Venemo
  • 18,515
  • 13
  • 84
  • 125
2

"Hello world!" is, in C (which C++ is based on), of type const char[] which then gets treated as a const char* when you try to use pointer arithmetic. In other words it's a memory address pointing to (say) the location OxDEAD0000 which contains the characters "Hello world!" and a null terminator.

"Hello world!" + id 

therefore resolves (if id is 8) to 0xDEAD0008

the stream operator then operates on the contents of this address, which is an offset of 8 characters into "Hello world!" - i.e. "rld!".

Airsource Ltd
  • 32,379
  • 13
  • 71
  • 75
  • thanx for this, but too much explain.. XD i only need to understood why that works in't that way.. =) – Andrea Bori Jun 02 '15 at 13:43
  • 5
    A [string literal's type](http://stackoverflow.com/q/18423201/1889329) is an array, not a pointer. However, an array can decay to a pointer to the first element, e.g. when used in pointer arithmetic. – IInspectable Jun 02 '15 at 13:44
2

You can either use operator<<

std::cout << "Hello world!" << id << std::endl;

Or if you have access to C++11 you can use std::to_string

std::cout << "Hello world!" + std::to_string(id) << std::endl;
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218