ChatGPT解决这个技术问题 Extra ChatGPT

Difference between \n and \r?

What’s the difference between \n (newline) and \r (carriage return)?

In particular, are there any practical differences between \n and \r? Are there places where one should be used instead of the other?

All the answers are fairly predictable, but I'd be interested to know if there are any PRACTICAL differences between \n and \r. Are there places where one should be used over the other?
well, yes, text files with only LF (newline) won't be seen as terminated in some Windows applications, and text files terminated with CRLF will appear to have extra characters if opened in some Linus applications.
yes, \r is used by some linux console apps to do rotating line animation.
Is \r really still the normal Mac EOL? I'm sure it was for "Classic" Mac, but I had thought OS X had Unixified. (Shows how familiar I am with Macs, eh?)
historically a \n was used to move the carriage down, while the \r was used to move the carriage back to the left side of the page.

A
AdrianHHH

In terms of ascii code, it's 3 -- since they're 10 and 13 respectively;-).

But seriously, there are many:

in Unix and all Unix-like systems, \n is the code for end-of-line, \r means nothing special

as a consequence, in C and most languages that somehow copy it (even remotely), \n is the standard escape sequence for end of line (translated to/from OS-specific sequences as needed)

in old Mac systems (pre-OS X), \r was the code for end-of-line instead

in Windows (and many old OSs), the code for end of line is 2 characters, \r\n, in this order

as a (surprising;-) consequence (harking back to OSs much older than Windows), \r\n is the standard line-termination for text formats on the Internet

for electromechanical teletype-like "terminals", \r commands the carriage to go back leftwards until it hits the leftmost stop (a slow operation), \n commands the roller to roll up one line (a much faster operation) -- that's the reason you always have \r before \n, so that the roller can move while the carriage is still going leftwards!-) Wikipedia has a more detailed explanation.

for character-mode terminals (typically emulating even-older printing ones as above), in raw mode, \r and \n act similarly (except both in terms of the cursor, as there is no carriage or roller;-)

In practice, in the modern context of writing to a text file, you should always use \n (the underlying runtime will translate that if you're on a weird OS, e.g., Windows;-). The only reason to use \r is if you're writing to a character terminal (or more likely a "console window" emulating it) and want the next line you write to overwrite the last one you just wrote (sometimes used for goofy "ascii animation" effects of e.g. progress bars) -- this is getting pretty obsolete in a world of GUIs, though;-).


To add to the history in this answer: as line speeds increased from 10 characters per second, it took more than 2 characters worth of time for the carriage to return and extra harmless characters (typically NUL i.e. \0) were added after the \n to allow the extra time. This was handled transparently by the OS so you won't find any traces of it in legacy code.
How is windows a 'weird' operating system?
@mailmindlin -- you ask "How is windows a 'weird' operating system?". Answer: in more ways than I can easily count (while wearing socks, so toes not allowed:-). All other surviving OS's are Unix-based... Windows's the one out, WAY out in many ways. In this specific Q's context -- it's the only one positing TWO bytes (\n\r) as the canonical line-end... for no sensible reason except the ancient-historical ones explained elsewhere on the thread... every other OS has a single char a5 line-end (99%+ of them `\n').
A small advice to all who will write a parser of some sort at some point in their lives - never forget to properly handle the ending of lines. I had some pretty nasty experience with that just because I forgot about the \r (I'm using Linux). Once I started parsing what seemed to be a valid file my parser failed because the file I was parsing has been created in Windows. :D The main problem in all that is that neither \n or \r are visible in the sense that for example a, ., ( etc. characters are.
"All other surviving OS's are Unix-based" not surprising considering they are all just some permutation of Unix. That's like saying vanilla is a weird ice cream flavour, because 100 people decided to sprinkle their chocolate ice cream with 100 different toppings and thus created 100 different flavours. I'm really getting tired of people comparing WIndows and Unix like they are supposed to be alternatives to each-other. That's like comparing a sports car to a tractor because they are both motor vehicles. And then claiming one is better than the other, period.
S
Sam

Historically a \n was used to move the carriage down, while the \r was used to move the carriage back to the left side of the page.


Perhaps not a terribly practical answer to a computer question, but the historical tidbit gets an upvote from me anyway.
Imagine \r to be similar to when you push the typing part of your physical typing machine to the left aka. return.
\n doesn't move the carriage down, it turns the roller to move the paper UP.
All movement is relative. The paper is my world, and relative to it, the carriage is moving down :P
FWIW, \r can still be a "Carriage Return" on modern systems. Consider this C code printf("abcdefghijlm\rNOP\n"); Compiled with gcc-8 on OpenSuSe and run on a terminal results in this output NOPdefghijlm. The \r (carriage return) in the string results in the cursor moving to the beginning of the line (carriage) and the characters following the \r (i.e. "NOP") overwrite what was previously there (i.e. the "abc")! You can achieve similar "carriage movement" with backspace (\b) as in printf("abcdefghijlm\b\bNOP\n"); which produces abcdefghijNOP
n
nishanthshanmugham

Two different characters.

\n is used as an end-of-line terminator in Unix text files

\r Was historically (pre-OS X) used as an end-of-line terminator in Mac text files

\r\n (ie both together) are used to terminate lines in Windows and DOS text files.


Notice that there are/was computers that used \n\r as end of line marker when you pressed the ENTER key, Like Acorn and RISC OS.
To clarify: \r hasn't been the line-ending on a Mac for a long time. With the release of Mac OS X in 2001 (which is Unix-based), \n is now used.
But there still some applications using \r - e.g. MS Office 2011 Excel: Saving a CSV (with all default settings) - will save an ISO-8859-1 encoded file with \r-line endings.
n
nothingisnecessary

Since nobody else mentioned it specifically (are they too young to know/remember?) - I suspect the use of \r\n originated for typewriters and similar devices.

When you wanted a new line while using a multi-line-capable typewriter, there were two physical actions it had to perform: slide the carriage back to the beginning (left, in US) of the page, and feed the paper up one notch.

Back in the days of line printers the only way to do bold text, for example, was to do a carriage return WITHOUT a newline and print the same characters over the old ones, thus adding more ink, thus making it appear darker (bolded). When the mechanical "newline" function failed in a typewriter, this was the annoying result: you could type over the previous line of text if you weren't paying attention.


The ASCII standard for newline is \r\n. (Apart from a brief interval when Bell Telephone got control of the standards committee). In return for the telephone monopoly, Bell Telephone gave up the messaging business (telegram, teletype), and did not care about existing use of the standard. HTTP, HTML, PCDOS and MSDOS used the ASCII standard. Bell Telephone chose to go non-standard for unix because they had no existing business to be compatible with.
Z
Ziad Amerr

Two different characters for different Operating Systems. Also this plays a role in data transmitted over TCP/IP which requires the use of \r\n.

\n Unix

\r Mac

\r\n Windows and DOS.


I think you are confusing with applicative protocols, TCP/IP has no idea of \n and \r .
TCP/IP does not require the use of \r\n. Various protocols based on Telnet require it, including SMTP, POP3, FTP, HTTP, ...
A
Akarun

To complete,

In a shell (bash) script, you can use \r to send cursor, in front on line and, of course \n to put cursor on a new line.

For example, try :

echo -en "AA--AA" ; echo -en "BB" ; echo -en "\rBB"

The first "echo" display AA--AA

The second : AA--AABB

The last : BB--AABB

But don't forget to use -en as parameters.


N
Neil Roy

In windows, the \n moves to the beginning of the next line. The \r moves to the beginning of the current line, without moving to the next line. I have used \r in my own console apps where I am testing out some code and I don't want to see text scrolling up my screen, so rather than use \n after printing out some text, of say, a frame rate (FPS), I will printf("%-10d\r", fps); This will return the cursor to the beginning of the line without moving down to the next line and allow me to have other information on the screen that doesn't get scrolled off while the framerate constantly updates on the same line (the %-10 makes certain the output is at least 10 characters, left justified so it ends up padded by spaces, overwriting any old values for that line). It's quite handy for stuff like this, usually when I have debugging stuff output to my console screen.

A little history

The /r stands for return or carriage return which owes it's history to the typewriter. A carriage return moved your carriage all the way to the right so you were typing at the start of the line.

The /n stands for new line, again, from typewriter days you moved down to a new line. Not nessecarily to the start of it though, which is why some OSes adopted the need for both a /r return followed by a /n newline, as that was the order a typewriter did it in. It also explains the old 8bit computers that used to have Return rather than Enter, from carriage return, which was familiar.


C
Community

What’s the difference between \n (newline) and \r (carriage return)? In particular, are there any practical differences between \n and \r? Are there places where one should be used instead of the other?

I would like to make a short experiment with the respective escape sequences of \n for newline and \r for carriage return to illustrate where the distinct difference between them is.

I know, that this question was asked as language-independent. Nonetheless, We need a language at least in order to fulfill the experiment. In my case, I`ve chosen C++, but the experiment shall generally be applicable in any programming language.

The program simply just iterates to print a sentence into the console, done by a for-loop iteration.

Newline program:

#include <iostream>

int main(void)
{
    for(int i = 0; i < 7; i++)
    {
       std::cout << i + 1  <<".Walkthrough of the for-loop \n";   // Notice `\n` at the end.
    }
    return 0;
}

Output:

1.Walkthrough of the for-loop
2.Walkthrough of the for-loop
3.Walkthrough of the for-loop
4.Walkthrough of the for-loop
5.Walkthrough of the for-loop
6.Walkthrough of the for-loop
7.Walkthrough of the for-loop

Notice, that this result will not be provided on any system, you are executing this C++ code. But it shall work for the most modern systems. Read below for more details.

Now, the same program, but with the difference, that \n is replaced by \r at the end of the print sequence.

Carriage return program:

#include <iostream>

int main(void)
{
    for(int i = 0; i < 7; i++)
    {
       std::cout << i + 1  <<".Walkthrough of the for-loop \r";   // Notice `\r` at the end.
    }
    return 0;
}

Output:

7.Walkthrough of the for-loop 

Noticed where the difference is? The difference is simply as that, when you using the Carriage return escape sequence \r at the end of each print sequence, the next iteration of this sequence do not getting into the following text line - At the end of each print sequence, the cursor did not jumped to the *beginning of the next line.

Instead, the cursor jumped back to the beginning of the line, on which he has been at the end of, before using the \r character. - The result is that each following iteration of the print sequence is replacing the previous one.

*Note: A \n do not necessarily jump to the beginning of following text line. On some, in general more elder, operation systems the result of the \n newline character can be, that it jumps to anywhere in the following line, not just to the beginning. That is why, they rquire to use \r \n to get at the start of the next text line.

This experiment showed us the difference between newline and carriage return in the context of the output of the iteration of a print sequence.

When discussing about the input in a program, some terminals/consoles may convert a carriage return into a newline implicitly for better portability, compatibility and integrity.

But if you have the choice to choose one for another or want or need to explicitly use only a specific one, you should always operate with the one, which fits to its purpose and strictly distinguish between.


D
DeyaEldeen

Just to add to the confusion, I've been working on a simple text editor using a TextArea element in an HTML page in a browser. In anticipation of compatibility woes with respect to CR/LF, I wrote the code to check the platform, and use whichever newline convention was applicable to the platform.

However, I discovered something interesting when checking the actual characters contained in the TextArea, via a small JavaScript function that generates the hex data corresponding to the characters.

For the test, I typed in the following text:

Hello, World[enter]

Goodbye, Cruel World[enter]

When I examined the text data, the byte sequence I obtained was this:

48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 0a 47 6f 6f 64 62 79 65 2c 20 43 72 75 65 6c 20 57 6f 72 6c 64 0a

Now, most people looking at this, and seeing 0a but no 0d bytes, would think that this output was obtained on a Unix/Linux platform. But, here's the rub: this sequence I obtained in Google Chrome on Windows 7 64-bit.

So, if you're using a TextArea element and examining the text, CHECK the output as I've done above, to make sure what actual character bytes are returned from your TextArea. I've yet to see if this differs on other platforms or other browsers, but it's worth bearing in mind if you're performing text processing via JavaScript, and you need to make that text processing platform independent.

The conventions covered in above posts apply to console output, but HTML elements, it appears, adhere to the UNIX/Linux convention. Unless someone discovers otherwise on a different platform/browser.


I
Ian Boyd

Carriage Return: returns the carriage to the start of the line

Line feed: feed the paper up one line

In the context of screen output:

CR: returns the cursor to the start of the current line

LF: moves the cursor down one line

For example:

Hello,\nworld\r!

is supposed to render on your terminal as:

Hello,
!     world

Some operating systems may break compatibility with the intended behavior, but that doesn't change the answer to the question "Difference between \n and \r?".


k
karthik gorijavolu
#include <stdio.h>

void main()
{
  int countch=0;
  int countwd=1;

  printf("Enter your sentence in lowercase: ");
  char ch='a';
  while(ch!='\r')
  {
    ch=getche();
    if(ch==' ')
      countwd++;
    else
      countch++;
  }

  printf("\n Words = ",countwd);

  printf("Characters = ",countch-1);

  getch();

}

lets take this example try putting \n in place of \r it will not work and try to guess why?


This only works if your underlining OS sends \r\n when you press the ENTER key, like MS DOS, DECS TOPS-10, CP/M, RT-11 etc. In OS:es like Multic, Unix and Unix-like(Linux, Minix etc) BeOS, RISCOS etc ENTER key only send you a \n character.
ahh yes the good old days when keyboards used to have both Return and Enter. Even my modern wireless keyboard still shows the down-and-back arrow on the old Return key (which is now titled "Enter" to be consistent with the numeric keypad's Enter key, which does not show the arrow)
In "modern languages", such errors / problematic code can still be evident when splitting lines on \r\n instead of \r?\n .. such can be found in windows code bases in language runtimes that don't offer a virtual newline.