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?
\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.