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

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;
}

Leave a Comment