string question, format

Hello I am following the plularsight c++ tutorials, and I am on the one about strings, but I have came across a part of code I do not understand, the person has explained why it is done this way, but not why it can not be done another way, I am hoping someone could clear this up for me.

So the piece of code is

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  #include <iostream>
#include <string>
using namespace std;

int main()
{
	string name;
	cout <<"Who are you?";
	cin>> name;
	string greeting = "hello " + name;
	if (name == "bob")
	{
		greeting += ", I know you";
	}
	cout << greeting << endl;
	return 0;
}


And the line of code that is causing me issues is the one below, I do not understand why I have to use += in this way, and why I can not use either of the other two methods I have shown below, like I do with other parts of code? Could someone please explain this?


1
2
3
4
5
    greeting += ", I know you";

    greeting + ", I know you";

    greeting << ", I know you";

+= means 'add this to what is already there'

greeting += "words";
is the same as
greeting = greeting + "words";

+ will not work.
consider it with integers:
int x =3;
int y = 4;
x+y; //what do you think this does? Where is the result??
now consider
x+= y; //this adds y to x, x is now 7. but the above has no assignment operations!

the same is true for strings.

<< is not set up to feed a string this way. There is a string stream type that is set up to work this way, but its a different object/type.
Last edited on
[nevermind, jonnin if you delete your post I can delete mine]
Last edited on
yea I corrected -- was thinking streams.
Thank you, the example helped me understand this.
Topic archived. No new replies allowed.