d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > I Cannot Determine What This Does!
Add Reply New Topic New Poll
Member
Posts: 3,706
Joined: Mar 8 2009
Gold: 17,175.10
Aug 31 2012 11:02am
#include <stdio.h>

int main() {

double value, total = 0;
char answer, dummy;

printf("Does anyone have any money?\n");
scanf("%c",&answer);
while (answer == 'y' || answer == 'Y') {

printf("Enter the amount of your donation.\n");
scanf("%lf",&value);
total += value;

printf("Does anyone have any money?\n");
scanf("%c%c",&dummy,&answer);
}

printf("As a group, you have collected $%lf for beer.\n",
total);
system("pause");
return 0;
}


I understand what the program is doing, up until it asks again "Do you have any money?" My problem is that I do not input a value for "%c",&dummy. I understand this has something to do with the while loop, because when I remove &dummy, the loop ends once you answer the second "Do you have any money?". I can't figure out what "%c",&dummy are actually doing during the process. I also could not find any materials on dummy variables that explained what this function does.

Thanks a bunch!
Member
Posts: 13,425
Joined: Sep 29 2007
Gold: 0.00
Warn: 20%
Aug 31 2012 11:46am
dont have time to test but i think its just storing the current scanf buffer char inside dummy then putting your n or y char inside answer.

when you scanf it stores the char you type as well as any other key (aka it also stores the enter key you pressed) but since you only accepted 1 char in the beginning ('y') the enter key is stored in the scanf buffer. what the second scanf statement simple clears the enter key in the scanf buffer and then puts the actual key you pressed inside answer.

ex:

scanf buffer: ""
does anyone have money
scanf buffer: "y{enter}"
put first char of buffer inside variable 'answer'
scanf buffer: "{enter}"
does anyone have money
scanf buffer: "{enter}y{enter}"
put first char of buffer inside dummer variable then second char of buffer inside answer
scanf buffer: "{enter}"
does anyone have money
scanf buffer: "{enter}y{enter}"
put first char of buffer inside dummer variable then second char of buffer inside answer
scanf buffer: "{enter}"

and it goes on.

hopefully you understand now.

a better way is to use the flushall(); function that flushes all the buffers. your new code would look like

Code
while (answer == 'y' || answer == 'Y') {

printf("Enter the amount of your donation.\n");
scanf("%lf",&value);
total += value;
flushall();
printf("Does anyone have any money?\n");
scanf("%c",&answer);
}


or something like that.

This post was edited by AbDuCt on Aug 31 2012 11:47am
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll