0
#include <stdio.h>

int main() {
    float change = 0.0;

    printf("O hai!  ");
    while (change <= 0) {
        printf("How much change is owed?\n");
        scanf("%f\n", &change);
    }
    return 0;
}

and the result if input is a negative is endless "How much change is owed?"

David Ranieri
  • 37,819
  • 6
  • 48
  • 88
Khanh
  • 439
  • 5
  • 5

2 Answers2

1

When you ask a computer to discard whitespace, how does it know what it's done? Answer: As soon as it reads something that's not whitespace.

You asked it to discard whitespace after reading a number. Thus it's not done until it reads the number and then reads some non-whitespace.

That really doesn't make any sense since there's no reason anyone would enter non-whitespace after entering the number.

Here's a tip though that will save you pain in the future: If what you really want to do is read a line of input then parse it, use a function that reads a line and then some code to parse that input.

David Schwartz
  • 173,634
  • 17
  • 200
  • 267
1

scanf is actually entered, but due to the \n in format string "%f\n", after having entered a number, scanf waits for the next non-whitespace character to return. Note that a white space in format specifier lets scanf consume a sequence of any white space characters, not only one, and so it "hangs" as long as only white space characters are provided by the stream.

Change scanf("%f\n",&change) into scanf("%f",&change).

VHS
  • 9,185
  • 3
  • 17
  • 41
Stephan Lechner
  • 34,359
  • 4
  • 30
  • 55