Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is \r in C language?

Tags:

c

#include <stdio.h>

int 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 =%d ",countwd);

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

  getch();
}

This is the program where I came across \r. What exactly is its role here? I am beginner in C and I appreciate a clear explanation on this.

like image 946
GEEK max Avatar asked Mar 10 '12 01:03

GEEK max


People also ask

Whats does \r do?

In most computer languages “\r” represents a “carriage return”. The two characters when entered into a computer program will be replaced by a single character with the ASCII code of 13. This is a “hidden” character, since it doesn't actually print anything on the screen, typically.

Is \r and \n the same?

They're different characters. \r is carriage return, and \n is line feed. On "old" printers, \r sent the print head back to the start of the line, and \n advanced the paper by one line. Both were therefore necessary to start printing on the next line.


2 Answers

'\r' is the carriage return character. The main times it would be useful are:

  1. When reading text in binary mode, or which may come from a foreign OS, you'll find (and probably want to discard) it due to CR/LF line-endings from Windows-format text files.

  2. When writing to an interactive terminal on stdout or stderr, '\r' can be used to move the cursor back to the beginning of the line, to overwrite it with new contents. This makes a nice primitive progress indicator.

The example code in your post is definitely a wrong way to use '\r'. It assumes a carriage return will precede the newline character at the end of a line entered, which is non-portable and only true on Windows. Instead the code should look for '\n' (newline), and discard any carriage return it finds before the newline. Or, it could use text mode and have the C library handle the translation (but text mode is ugly and probably should not be used).

like image 61
R.. GitHub STOP HELPING ICE Avatar answered Oct 13 '22 04:10

R.. GitHub STOP HELPING ICE


It's Carriage Return. Source: http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx

The following repeats the loop until the user has pressed the Return key.

while(ch!='\r')
{
  ch=getche();
}
like image 25
Luchian Grigore Avatar answered Oct 13 '22 04:10

Luchian Grigore