a problem in c in gcc 4.1.2
hi guys!!!!!!
i have a problem in c in gcc-4.1.2 the problem is #include<stdio.h> int main() { int x=10; char ch; do { printf("%d",x); printf("\nDo you want it again? "); scanf("%c",&ch); //problem is here }while(ch=='y'||ch=='Y'); return 0; } on compiling and running it, the output is as shown [bryan@laptop ~]$ gcc test_do_while.c -o test_do_while.o [bryan@laptop ~]$ ./test_do_while.o 10 Do you want it again? y 10 Do you want it again? [bryan@laptop ~]$ The second time it does not wait for a character to be entered not even with getch() and fgetc(stdin) but if i add a space in the scanf statement of ch as shown #include<stdio.h> int main() { int x=10; char ch; do { printf("%d",x); printf("\nDo you want it again? "); scanf(" %c",&ch); //space added before %c inside double quotes }while(ch=='y'||ch=='Y'); return 0; } the program works fine............. the problem is same with other loops too............. adding the space there removes the problem........... can anyone tell me the reason for this......please......... |
Because in the first case it reads the newline character too, when you press Enter.
man scanf explains it here: Code:
c Matches a sequence of characters whose length is specified by |
uncle_theoddre (sorry for spelling mistake) is right. the '\n' character gets qued up and is accepted as the arguement when the second time scanf statement is executed.
you can add the statement fflush(stdin); this would flush up the standard input buffer so u won't have any problem but this is not a permanent solution as fflush statement sometimes does not seem to function properly.....okay.....so use at your own risk!!!!!!!!!!! hugs and codes author_unknown |
author_unknown,
I'm no expert in C, but according to what I've read before, fflush() is meant for output streams, not input. If I'm correct, it won't work that way. Does anyone have a different experience? |
well mimithebrain,
its not so u can use fflush for stdin also but sometimes it may happen dat fflush is unable to flush the input buffer, i dont know the reason but its true....... |
Yours is a variation on the popular 'character-at-time' terminal IO problem, or what I like to call the 'getch()' problem. Google search for "character-at-a-time IO" for a long list of solutions and descriptions of the issues involved. Searching for 'getch' in this forum will also lead to informative threads.
--- rod. |
All times are GMT -5. The time now is 05:05 PM. |