Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't pressing enter return '\n' to getch()?

Tags:

c

input

#include <stdio.h>
#include <conio.h>
main()
{
    char ch,name[20];
    int i=0;
    clrscr();
    printf("Enter a string:");
    while((ch=getch())!='\n')
    {
        name[i]=ch;
        i++;
    }
    name[i] = '\0';
    printf("%s",name);
}

When I give "abc" as input and if I press enter it's not working. Can anyone let me know why the condition ch=getch() != '\n' is not becoming false when I press enter? I have also observed that ch is taking \r instead of \n. Kindly let me know. Thanks

like image 565
user58349 Avatar asked Jan 23 '09 16:01

user58349


1 Answers

Use '\r' and terminate your string with '\0'.

Additionally, you might try to use getche() to give a visual echo to the user and do some other general corrections:

#include <stdio.h>
#include <conio.h>

#define MAX_NAME_LENGTH 20

int main()
{
    char ch, name[MAX_NAME_LENGTH];
    int i=0;
    clrscr();
    printf("Enter a string:");
    while ( ((ch=getche())!='\r') && (i < MAX_NAME_LENGTH - 1) )
    {
        name[i]=ch;
        i++;
    }
    name[i] = '\0';
    printf("%s\n",name);

    return 0;
}
like image 143
schnaader Avatar answered Nov 10 '22 17:11

schnaader