Confusion on \n and enter key

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ariharan
    New Member
    • Aug 2007
    • 20

    Confusion on \n and enter key

    see this progrmmmmm
    [CODE=c]void main()
    {
    char ch;
    printf("enter the string");
    do
    {
    ch=getchar();
    } while(ch!='\n') ;
    getch();
    }[/CODE]

    here that do while loops end when we press the "enter key"
    but wht is my question is ascii value of "enter key" is 13..
    while asccii of '\n ' is 10
    how this possible
    this program still runs

    plz any one say the reson behind this
    Last edited by Ganon11; Feb 16 '08, 04:46 PM. Reason: Please use the [CODE] tags provided.
  • ashitpro
    Recognized Expert Contributor
    • Aug 2007
    • 542

    #2
    Originally posted by Ariharan
    see this progrmmmmm
    void main()
    {
    char ch;
    printf("enter the string");
    do
    {
    ch=getchar();
    }while(ch!='\n' );
    getch();

    }

    here that do while loops end when we press the "enter key"
    but wht is my question is ascii value of "enter key" is 13..
    while asccii of '\n ' is 10
    how this possible
    this program still runs

    plz any one say the reson behind this

    Well,
    here you have to understand how getchar() works.
    when you issues a getchar().
    getchar() waits for a "character+ente r key" , however if you enter "string+ent er key" it will consider a first character of a string you entered.
    Now result will be put in 'stdin' as "character you entered+\n"
    In simple language we can say that it converts "enter key" to '\n'.
    So when you hit only enter key. your 'ch' variable will end up with having '\n' in it.
    If you don't want this behaviour, use
    ch = getch() or ch = getche(), instead of ch=getchar();
    In former case your will see the '13' value in 'ch' variable.
    and of course in later case 'ch' will have '10' i.e '\n'.
    that's why your loop gets terminated

    Comment

    Working...