Dean
Dean

Reputation: 8065

C: Scanf in while loop executes only once

I am trying something simple in C, a program to get the exchange and do some conversions. To make sure scanf gets the right type I placed it into a while loop, which continues to ask for input until a number is inserted. If I enter a character instead of a number it does not ask again for an input.

exRate = 0;
scanfRes = 0;

while(exRate <= 0){
    printf("Enter the exchange rate:");
    while(scanfRes != 1){
        scanfRes = scanf(" %f", &exRate);
    }


    if(scanfRes == 1 && exRate > 0){
        break;
    }

    printf("Exchange rate must be positive.\n");
}

UPDATE: As this is a course assignment, I was not supposed to use anything outside of the taught material. When I asked the academic staff about handling unexpected input, I got an answer that this is a scenario I am not supposed to take into consideration.

The answers and help in the comments is all useful and I added 1 to all useful suggestions. The staff answer makes this question no longer needed.

Upvotes: 0

Views: 407

Answers (1)

chux
chux

Reputation: 153468

Change handling of scanf() result.

If the input is not as expected, either the offending input data needs to be read or EOF should be handled.

for (;;) {
    printf("Enter the exchange rate:");
    scanfRes = scanf("%f", &exRate);
    if (scanfRes == 0) {
      printf("Exchange rate must be numeric.\n");
      // somehow deal with non-numeric input, here just 1 char read & tossed
      // or maybe read until end-of-line
      fgetc(stdin);
    } else if (scanfRes == EOF) {
      // Handle EOF somehow
      return;   
    } exRate > 0){
      break;
    }
    printf("Exchange rate must be positive.\n");
 }

Note: the " " in " %f" is not needed. "%f" will consume leading white-space.

Upvotes: 1

Related Questions