468,513 Members | 941 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,513 developers. It's quick & easy.

Confusion on \n and enter key

see this progrmmmmm
Expand|Select|Wrap|Line Numbers
  1. void main()
  2. {
  3.   char ch;
  4.   printf("enter the string");
  5.   do 
  6.   {
  7.     ch=getchar();
  8.   } while(ch!='\n');
  9.   getch();
  10. }
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
Feb 16 '08 #1
1 12105
ashitpro
542 Expert 512MB
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+enter key" , however if you enter "string+enter 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
Feb 16 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

38 posts views Thread by Grant Edwards | last post: by
2 posts views Thread by Bill C. | last post: by
8 posts views Thread by Z D | last post: by
9 posts views Thread by William LaMartin | last post: by
tolkienarda
14 posts views Thread by tolkienarda | last post: by
8 posts views Thread by carlos123 | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.