Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "\n" give a new line on Windows?

The line-break marker on Windows should be CR+LF whereas on Unix, it's just LF.

So when I use something like Console.Write("line1\nline2");, why would it work "properly" and give me two lines? I expect this \n not to work, and only a combo of \r\n would work.

like image 716
user1032613 Avatar asked Apr 05 '12 19:04

user1032613


People also ask

Does \n make a new line?

The \n Character The other way to break a line in C++ is to use the newline character — that ' \n ' mentioned earlier. This is line one. This is line two.

Does \n work on Windows?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF.

What is \n line break?

Newline (frequently called line ending, end of line (EOL), next line (NEL) or line break) is a control character or sequence of control characters in a character encoding specification (e.g., ASCII, EBCDIC) that is used to signify the end of a line of text and the start of a new one.

Why is there a carriage return in Windows?

In computing, the carriage return is one of the control characters in ASCII code, Unicode, EBCDIC, and many other codes. It commands a printer, or other output system such as the display of a system console, to move the position of the cursor to the first position on the same line.


2 Answers

'\n' is the Line Feed character. Traditionally, it caused the printer to roll the paper up one line. '\r' is the Carriage Return character, which traditionally caused the printer head to move to the far left edge of the paper.

On printers and consoles that interpret the characters in this manner, the output of line1\nline2 would be

line1      line2 

Many consoles (and editors) will interpret '\n' to mean that you want to start a new line and position the cursor at the beginning of that new line. That is what you see here.

You should use Environment.NewLine rather than hard-coding any particular constants.

like image 106
Eric J. Avatar answered Oct 07 '22 11:10

Eric J.


This is just the standard behaviour of the underlying Windows console. A native C app will do exactly the same if you output 0x0A to the console.

Of course, you should be using Environment.NewLine for your new lines. Environment.NewLine resolves to \r\n on Windows and \n on Unix like systems.

like image 25
David Heffernan Avatar answered Oct 07 '22 09:10

David Heffernan