| | |
C - Getting double output?
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Apr 2005
Posts: 105
Reputation:
Solved Threads: 3
I must be missing something here. I am having trouble when I try to get an input. The numbers work fine, but once you get the correct answer, the area:
isn't right. It will print "Would you like to try another (y/n)." "Invalid Choice." "Would you like to try another (y/n)" then wait for your input... why is it doing this?
Thank you.
Here is the rest of the code:
C Syntax (Toggle Plain Text)
void tryanother() { char yorn; printf("Would you like to try another one? (y/n)\n"); scanf("%c", &yorn); if (yorn == 'y') getnum(); else if (yorn == 'n') return; else if (yorn != 'y' || yorn != 'n') { printf("Invalid choice\n"); tryanother(); } }
isn't right. It will print "Would you like to try another (y/n)." "Invalid Choice." "Would you like to try another (y/n)" then wait for your input... why is it doing this?
Thank you.
Here is the rest of the code:
C Syntax (Toggle Plain Text)
#include <stdio.h> #include <stdlib.h> #include <time.h> void getnum (); void tryagain(int, int, int); void tryanother(); void getnum() { int num1, num2, solution; num1 = (rand() % 9); num2 = (rand() % 9); solution = num1 * num2; tryagain (num1, num2, solution); } void tryagain(int num1, int num2, int solution) { int guess; printf("How much is %d times %d ?\n", num1, num2); scanf("%d", &guess); if(guess == solution) { printf("Very Good!\n\n"); tryanother(); } else tryagain(num1, num2, solution); } void tryanother() { char yorn; printf("Would you like to try another one? (y/n)\n"); scanf("%c", &yorn); if (yorn == 'y') getnum(); else if (yorn == 'n') return; else if (yorn != 'y' || yorn != 'n') { printf("Invalid choice\n"); tryanother(); } } int main() { srand(time (NULL)); getnum(); return 0; }
when you press 'y' followed by <Enter> key, there are two keys in the keyboard buffer -- so the second time through the code it is probably getting the '\n' key. you need to flush the keyboard buffer to remove the '\n'.
or you could use fgets() which will flush the '\n' too assuming the user types on 'y' followed by <Enter>. If anything else is typed then those keys will also be in the keyboard buffer. There is no easy standard solution to the problem. Make the buffer in the code below big enough and fgets() will probably be able to fill it with all the keys in the buffer.
C Syntax (Toggle Plain Text)
scanf("%c", &yorn); getchar(); //flush the keyboard buffer of the '\n' key
or you could use fgets() which will flush the '\n' too assuming the user types on 'y' followed by <Enter>. If anything else is typed then those keys will also be in the keyboard buffer. There is no easy standard solution to the problem. Make the buffer in the code below big enough and fgets() will probably be able to fill it with all the keys in the buffer.
C Syntax (Toggle Plain Text)
char buf[3]; fgets(buf,sizeof(buf),stdin); yorn = buf[0];
With fgets(), you risk not flushing the entire buffer, and with a single getchar() you have the same problem. The best solution is this:
c has to be an int because EOF is an int value.
C Syntax (Toggle Plain Text)
int c; while((c = getchar()) != '\n' && c != EOF);
dwk
Seek and ye shall find.
"Only those who will risk going too far can possibly find out how far one can go."
-- TS Eliot.
"I have not failed. I've just found 10,000 ways that won't work."
-- Thomas Alva Edison
"The only real mistake is the one from which we learn nothing."
-- John Powell
Seek and ye shall find.
"Only those who will risk going too far can possibly find out how far one can go."
-- TS Eliot.
"I have not failed. I've just found 10,000 ways that won't work."
-- Thomas Alva Edison
"The only real mistake is the one from which we learn nothing."
-- John Powell
dwk
Seek and ye shall find.
"Only those who will risk going too far can possibly find out how far one can go."
-- TS Eliot.
"I have not failed. I've just found 10,000 ways that won't work."
-- Thomas Alva Edison
"The only real mistake is the one from which we learn nothing."
-- John Powell
Seek and ye shall find.
"Only those who will risk going too far can possibly find out how far one can go."
-- TS Eliot.
"I have not failed. I've just found 10,000 ways that won't work."
-- Thomas Alva Edison
"The only real mistake is the one from which we learn nothing."
-- John Powell
I did not understand that if the size of the buf variable is 3 then after getting input "y" and "\n" how does stdin terminate the coming input i.e. what would be buf[2]??
Also , I did not understand why
this is required. I have gone through faq recommended by dwks but still I am not clear . Please help,
Thanks,
comwizz.
C Syntax (Toggle Plain Text)
char buf[3]; fgets(buf,sizeof(buf),stdin); yorn = buf[0];
C Syntax (Toggle Plain Text)
while((c = getchar()) != '\n' && c != EOF);
Thanks,
comwizz.
lets say that instead of typing just y + '\n', you type a whole bunch of keys then '\n' at the end. fgets() will only grab from the keyboard buffer the number of keys that will fit in the buffer (sizeof the buffer - 1 for null terminator), the remaining keys will stay in the keyboard buffer until your program removes them. And the buffer returned by fgets() will contain '\n' only if there is one in the input stream.
The loop that dwks posted is probably the savest way to flush out (empty) the keyboard buffer that contains an unknown number of characters.
The loop that dwks posted is probably the savest way to flush out (empty) the keyboard buffer that contains an unknown number of characters.
![]() |
Similar Threads
- Vector with Multiple Memebers (C)
- Is there a stream class member equivalent to sprintf() (C)
- Using Decimal Numbers instead of Integers in C (C)
- pow: DOMAIN error (C++)
Other Threads in the C Forum
- Previous Thread: 2d array
- Next Thread: execvp return help...
| Thread Tools | Search this Thread |
#include adobe api array arrays asterisks binarysearch calculate char cm copyanyfile copyimagefile copypdffile cprogramme createcopyoffile createprocess() csyntax directory dynamic feet fflush fgets file fork forloop framework frequency getlasterror givemetehcodez global graphics gtkgcurlcompiling hacking hardware highest homework i/o incrementoperators kernel kilometer km linked linkedlist linux linuxsegmentationfault list lists locate logical_drives loopinsideloop. match matrix meter microsoft motherboard mqqueue multi mysql number odf open opensource openwebfoundation owf pattern pdf performance pointer pointers posix probleminc process program programming pyramidusingturboccodes read recursion recv repetition research scanf scheduling scripting segmentationfault send shape socket socketprograming stack standard string strings systemcall testautomation unix user voidmain() wab win32api windows.h






