Whats the difference between these 2 cout

What's the difference between


 
  cout << "You're awesome\n";


AND

 
  cout << "You're awesome" << "\n";
They do the same thing, but they look like:

1
2
3
operator<<(cout, "You're awesome\n");

operator<<(operator<<(cout, "You're awesome"), "\n");

oh okay.

But why bother having 2 ways of doing the same thing?

In the book i'm reading. I noticed in one code it uses

cout << "You're awesome\n";

in an int variable

whilst

cout << "You're awesome" << "\n";

in a string variable

It doesn't explain why though.
Consider this example:

1
2
3
cout << "Hello World"; // "Hello World" is printed entirely

cout << "Hello " << "World"; // "Hello " is printed first, then "World" is printed second 


So the final result is the same, but in the first case, the message is given at once.
The second case is used when you need to put something in between them:

1
2
3
string type_of_world = "Crazy ";

cout << "Hello " << type_of_world << "World"; 


It doesn't explain why though.

I think if you still have questions, you should copy-paste (or rewrite) the code from the book on this thread.
Last edited on
Here's the 2 codes that i was curious about.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
int num;
cout << "Enter number";
cin >> num;

if ( num < 0)
     { cout << "You have a positive number\n";
      }
   else
  { cout << "You have a negative number\n;
   }

} 


AND

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main ()
{
string username;
string password;
cout << "Enter username" << "\n";
getline (cin, username, '\n';

cout << "Enter pasword" << "\n;
getline (cin, password, '\n';

if ( username == "octopus" && password == "dog"
{ cout << "Correct details" << "\n";
}

else 
{ cout << "Incorrect details" << "\n";
 }

} 
The second code contains mistakes and will not compile.
Lines 6, 8, 9, 11.

To answer the question, from what I see the author didn't have a true reason to split the message and "\n".

Maybe the author thought he would make the message easier to read.
Maybe he originally used std::endl and then decided to replace it with "\n".

1
2
3
4
5
6
7
8
9
10
11
// std::endl will put a '\n' then flush the stream,
// and so it shouldn't be overused

cout << "Correct details" << endl;
cout << "Incorrect details" << endl;

// author realizes this is clumsy...
// and does a Replace endl with "\n"

cout << "Correct details" << "\n";
cout << "Incorrect details" << "\n";

Topic archived. No new replies allowed.