Where to use the n in the printf?

Asked

Viewed 71 times

-1

Hi, my question is where to put the \n.

I see several situations where the \n is used at the end of printf:

int x = 2, y = 3;

printf("X = %d\n",x);

printf("Y = %d",y);

But also, I see it being used in the beginning:

int x = 2, y = 3;

printf("X = %d",x);

printf("\nY = %d",y);

I’d like to know if:

There’s a difference in putting the \n at the beginning or end of printf?

Some of these methods are more recommended?

And if I want to skip two or more lines, I put several \n followed or there’s some other way?

From now on, thank you very much.

  • 2

    "There is difference in putting n at the beginning or at the end of the printf?" - Yes, if you put it in the beginning, first it skips the line and then it writes the rest, and if you put it in the end, first it writes everything and at the end it skips the line. In your specific example it makes no difference, of course, and there is no "recommendable" one, it all depends on what you need. Put \n when you want to skip the line, it does not matter if it is in the "beginning" or the "end". Just for the record, in your case it would be done in a single command: printf("X = %d\nY = %d", x, y);

  • But what if I want to skip several lines? I put several \n?

  • The character ' n' is passed to the next line. If you use 2 consecutive lines the result is a blank line. If 3 consecutive then 2 blank lines and so on. Nothing that a simple test would not clarify.

  • Yes, to skip several lines, put several \n. You tried to? :-) If "several" are really many, then maybe it’s worth making a loop: for (int i = 0; i < qtdLinhas; i++) printf("\n") - but if it’s only 2 or 3, it doesn’t even pay to do it, put \n\n even...

  • Yeah, I took the test and I knew it worked, I just wanted to know if there was any function, or anything like that, to skip several lines without having to type several times \n or having to use a loop, but thanks for the clarification

1 answer

0


The \n means line break, when you put it in your string means you want to skip a line, because for the compilador if you skip several lines or no line for it is the same thing, with \n you can tell him that had a line break, it would be similar to tag <br> in the html.

Code ex C++:

...
cout << "Boa tarde" << endl;
cout << "Tudo bem?" << endl;
...
Saída:

Boa tarde
Tudo bem?
...
cout << "Boa tarde\n" << endl;
cout << "Tudo bem?" << endl;

Saída:

Boa tarde

Tudo bem?
...

There’s only one line break, so it makes no difference to the code where the \n(not required to use), it is only useful for better viewing of outputs.

  • Okay, thank you very much for your attention and willingness to answer my question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.