' \r ' vs ' \n ' in C

Posted by MCP on Stack Overflow See other posts from Stack Overflow or by MCP
Published on 2012-04-07T23:15:53Z Indexed on 2012/04/07 23:29 UTC
Read the original article Hit count: 155

Filed under:

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? Ie the user would literally have to enter "\n" from the console, correct? Thanks!

© Stack Overflow or respective owner

Related posts about c