I'm writing a function that basically waits for the user to hit "enter" and then does something. What I've found that works when testing is the below:
#include <stdio.h> int main() { int x = getc(stdin); if (x == '\n') { printf("carriage return"); printf("\n"); } else { printf("missed it"); printf("\n"); } }
The question I have, and what I tried at first was to do: if (x == '\r')
but in testing, the program didn't catch me hitting enter. The '\n'
seems to correspond to me hitting enter from the console. Can someone explain the difference? Also, to verify, writing it as if... == "\n"
would mean the character string literal? i.e. the user would literally have to enter "\n"
from the console, correct?
A carriage return would do exactly that, return the print head carriage to the beginning of the line. A newline character would simple shift the roller to the next line without moving the print head.
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.
A line feed means moving one line forward. The code is \n . A carriage return means moving the cursor to the beginning of the line. The code is \r .
'\r' is the representation of the special character CR (carriage return), it moves the cursor to the beginning of the line. '\n'(line feed) moves the cursor to the next line . On windows both are combined as \r\n to indicate an end of line (ie, move the cursor to the beginning of the next line).
The '\n' is the "Line Feed" and '\r' is the carriage return. Different operating systems will handle new lines in a different way, such as
Windows
Expects a newline to be combination of two characters, '\r\n'.
Linux\Unix and Modern Mac OS
Uses a single '\n' for a new line.
Classic Mac OS
Uses a single '\r' for a new line.
Basically, I would use if (x == '\n')
as it is currently used by all modern operating systems.
\n
is the newline character, while \r
is the carriage return. They differ in what uses them. Windows uses \r\n
to signify the enter key was pressed, while Linux and Unix use \n
to signify that the enter key was pressed.
Thus, I'd always use \n
because it's used by all; and if (x == '\n')
is the proper way to test character equality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With