I found this weird problem which I hadn't seen before. I was working on Cygwin (the problem later replicated on a real linux box as well). I was writing a program where I needed to do something like:
Now my problem is that this loops only once whatever input I give. The first time it loops correctly, the 2nd time it gets into the lopp and exits after the printf. I tried using fflush() but that didn't help either. Am I doing something really stupid?
while(ch == 'y')
x = myfunc();
//do something ...
printf("\n Enter y to insert again:");
scanf("%c",&ch); // I tried using getchar() and getch() also.
I am guessing there is something left in the buffer that scanf reads in the second time around. Have a look at the following FAQs:
FAQ > Explanations of... > Why fflush(stdin) is wrong
FAQ > How do I... (Level 2) > Flush the input buffer
FAQ > How do I... (Level 1) > Get a line of text from the user/keyboard (C)
You might also want to check out some of Dave Sinkula's articles beginning with this one.
That should get you started anyway. Generally what it comes down to is that you end up rolling your own function, incorporating some of the library functions, to suit your particular needs.
Hmm, all this while I hadn't known this. I never saw scanf behaving like that before. Is it because of the while loop?
>>Is it because of the while loop?
Yes, kind of, more specifically because the newline left in the input buffer is a
char. Read this thread where I descibed what's happening in detail.