Question about cout << endl statements

How come in these line of code the endl code precedes the << string ;? Meaning why did the author of my textbook structured the statement cout << endl << string; rather than cout << string << endl; like how most C++ textbook do it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int main() {	
	int nil = 0, num = 0, max = 1; char cap = 'A', low = 'a';
	
	cout << "Equality comparisons: ";
	cout << "(0==0)" << (nil == num) << "(true)";
	cout << "(A==a)" << (cap == low) << "(false)";
	
	cout << endl << "Inequality comparison: ";
	cout << "(0 != 1)" << (nil != max) << "(true)";
	
	cout << endl << "Greater comparison: ";
	cout << "(0 > 1)" << ( nil > max) << "(false)";
	
	cout << endl << "Lesser comparison: ";
	cout << "(0 < 1)" << (nil < max) << "(true)";
	
	cout << endl << "Greater or equal comparison: ";
	cout << "(0 >= 0)" << (nil >= num) << "(true)";
	
	cout << endl << "Lesser or equal comparison: ";
	cout << "(1 <= 0)" << (max <= num) << "(fasle)";
	
	return 0;
}
For no particular reason, I would expect.

But looking at it, it's more compact than

7
8
9
10
11
12
13
14
15
16
	cout << "Equality comparisons: ";
	cout << "(0==0)" << (nil == num) << "(true)";
	cout << "(A==a)" << (cap == low) << "(false)";
        cout << endl;
	
	cout << "Inequality comparison: ";
	cout << "(0 != 1)" << (nil != max) << "(true)";
        cout << endl;

        // etc 


or

7
8
9
10
11
12
13
14
	cout << "Equality comparisons: ";
	cout << "(0==0)" << (nil == num) << "(true)";
	cout << "(A==a)" << (cap == low) << "(false)" << endl;
	
	cout << "Inequality comparison: ";
	cout << "(0 != 1)" << (nil != max) << "(true)" << endl;

        // etc 


Andy
Hi Andy, i guess that makes sense. But what does have a endl keyword before the string do to the statement( endl << string; )?
It means there's a new line just before the string is output.

endl inserts a new line char ('\n') into the stream and calls ostream::flush(), wherever it is in a chain of calls.

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

int main() {
    int a = 1, b = 2, c = 3, d = 4;

    cout << a << endl
         << endl << b << endl
         << endl << endl << c << endl << endl
         << d << endl;

    return 0;
}


Andy
Okay, got it thanks Andy!
It is simply adding a new line before outputting the text. It is basically combining 2 lines of code into one single of code:

1
2
cout << endl;
cout << "Text";
Side note: endl is really overused. Just output a "\n" in the right spots, and flush when you know you need to.
Topic archived. No new replies allowed.