1

I have wrote some code to calculate what type and amount of bills to be returned to the customer given their amount owed and amount paid. The implementation of change() is in another file (change.c).

#include <stdio.h>
#include "change.h"

int main() {
    double bill, pay;
    char temp;
    temp = getchar();
    while (temp != EOF){
        ungetc(temp, stdin);
        scanf("%lf%lf", &bill, &pay);
        change(bill, pay);
        temp = getchar();
    }
    
    return 0;
}

My problem is that when I tried terminate the program with crtl+d, an extra set of output is printed.

3.5 69.1 //input from stdin
Change of:
1 fifty dollar bill
0 twenty dollar bill
7 two dollar coin
15 dime
1 nickel
4 12.4 //input from stdin
Change of:
0 fifty dollar bill
0 twenty dollar bill
4 two dollar coin
4 dime
1 nickel
Change of:
0 fifty dollar bill
0 twenty dollar bill
4 two dollar coin
4 dime
1 nickel

2 inputs but 3 outputs (last output is the same as the second last output). I have spent hours investigating but cannot figure out why. Any help would be greatly appreciated!

  • Debug your program and put a breakpoint on the `ungetc` call to inspect `temp` (where you'll likely see the newline you hit before you entered ctrl-D, but didn't bother mentioning). Also, your `scanf` is naively assumptive. You never check whether it actually parsed your two arguments successfully, and it is pointless to invoke `change`, or continue the loop for that matter, if it did not. – WhozCraig Feb 03 '22 at 02:24
  • 1
    Because `scanf` leaves the newline character in the buffer. Then `getchar` reads the newline, `ungetc` puts the newline back, and `scanf` skips the newline and immediately reads EOF. So `bill` and `pay` are not changed, and the `change` function gets the same parameters. – user3386109 Feb 03 '22 at 02:26
  • 3
    The correct way to write the loop is `while (scanf("%lf%lf", &bill, &pay) == 2) { change(bill, pay); }` – user3386109 Feb 03 '22 at 02:28
  • `temp` should be an int, and have a more meaningful name. – Retired Ninja Feb 03 '22 at 02:38

0 Answers0