Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ interesting syntax for printing new line in std::cout [duplicate]

the following code prints a square of '*' characters:

int m = 5; int n=5;
for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
        std::cout << "*" << " \n"[j==5];

Output:

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

My question is regarding to the " \n"[j==5] part. Does anyone know how exactly does this syntax work?

like image 677
ibezito Avatar asked May 14 '17 08:05

ibezito


People also ask

How do you print two things on the same line in C++?

You are inserting std::endl which prints next string on the next line. The following newline \n and std::flush is equivalent to std::endl . std::cout << printFunction() << std::endl; Now removing std::endl will print the string in the same line.

How do you print a line in C++?

The symbol \n is a special formatting character. It tells cout to print a newline character to the screen; it is pronounced “slash-n” or “new line.”

What is better printf or cout?

cout is a object for which << operator is overloaded, which send output to standard output device. The main difference is that printf() is used to send formated string to the standard output, while cout doesn't let you do the same, if you are doing some program serious, you should be using printf().

How do you stop cout without a new line?

The cout operator does not insert a line break at the end of the output. One way to print two lines is to use the endl manipulator, which will put in a line break. The new line character \n can be used as an alternative to endl. The backslash (\) is called an escape character and indicates a special character.


1 Answers

" \n" is array of 3 chars. You can index is as normal array. Boolean values implicitly convert to integers: false to 0, true to 1. So it will use '\n' for j == 5 and ' ' if not,

like image 130
P. Dmitry Avatar answered Oct 21 '22 04:10

P. Dmitry