-6

Here is a program that "works", but will go into an infinite loop if character data "a" is entered or "-8" is entered.

Here is the expected output when data is entered into the program:

****Input (sales)   EXPECTED OUTPUT****
input: 5000.00      output: 650.00 
input: 1234.56      output: 311.11 
input: 1088.89      output: 298.00 
input: 0            output: 200.00 
input: 'a'          output: Warning and prompt to re-enter
input: -8           output: Warning and prompt to re-enter
input: -1           output: End Program

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>

int main() {
  float sales, commission, earnings;

  while(true) {
    printf( "Enter sales in dollars ( -1 to end ): " );
    scanf( "%f", &sales );

    if ( sales == -1 ) {
      return 0;
    }

    commission = sales / 100 * 9;
    earnings = commission + 200;

    printf( "Salary is %.2f\n", earnings );
  }

  return 0;
}

Thanks. Total newb and appreciate the help.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Johnny311
  • 1
  • 3

1 Answers1

0

Check return value of scanf and clear input buffer in case of illegal input.

Like this:

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    float sales, commission, earnings;
    int state;

    while(true) {
        printf( "Enter sales in dollars ( -1 to end ): " );
        if((state = scanf("%f", &sales )) != 1){
            if(state == EOF)
                return 0;
            printf("invalid input.\n");
            while(getchar() != '\n');//clear input

            continue;
        }

        if ( sales == -1 ) {
            return 0;
        } else if(sales < 0){
            printf("invalid input.\nA negative value was entered.\n");
            continue;
        }

        commission = sales / 100 * 9;
        earnings = commission + 200;

        printf( "Salary is %.2f\n", earnings );
    }

    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70