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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In terms of ascii code, it’s 3 — since they’re 10 and 13 respectively;-).
But seriously, there are many:
\nis the code for end-of-line,\rmeans nothing special\nis the standard escape sequence for end of line (translated to/from OS-specific sequences as needed)\rwas the code for end-of-line instead\r\n, in this order\r\nis the standard line-termination for text formats on the Internet\rcommands the carriage to go back leftwards until it hits the leftmost stop (a slow operation),\ncommands the roller to roll up one line (a much faster operation) — that’s the reason you always have\rbefore\n, so that the roller can move while the carriage is still going leftwards!-) Wikipedia has a more detailed explanation.\rand\nact 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\ris 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;-).