According to the ASCII table, value of the new line character(\n) is 13 whereas value of Carriage Return (CR) is 13 . When trying to write a program that detects if enter key is pressed. ıs it safe to use the either value ?
if( ( kr=getchar() ) == 13 )
puts("Enter Key Pressed ") ;
or
if( ( kr=getchar() ) == '\n' )
puts("Enter Key Pressed ") ;
Short answer: you should always use '\n'
.
Longer answer: Yes, Carriage Return is ASCII 13 is '\r'
in C.
Newline is ASCII 10 (not 13) and is '\n'
in C.
But the key you press is not necessarily the same as the character you'll receive in a C program, for two reasons:
'\n'
. Even if the underlying operating system has different conventions, under normal circumstances your program is supposed to receive a '\n'
for a new line. (Similarly, when you print a '\n'
, it gets translated to carriage return, linefeed, or a carriage return / linefeed pair, depending on your OS's conventions.)Finally, whatever you do, even if you do need to handle Carriage Returns explicitly, please use '\r'
and '\n'
in C programs. Don't make your readers know what the magic numbers 10 and 13 (or 0x0a and 0x0d) are.