#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
The actual meaning of
\n
is\r
+\n
.getch()
function reads a character from the keyboard.It does not echo it and does not wait for next character.
So whenever we enter
\n
charactergetch()
function reads\r
character only.That is because the return key on your keyboard is represented internally as '\r' not '\n'. In order for that specific example to work, you would need to trap '\r' instead.
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: