C程序与scanf进入无限循环

时间:2017-09-11 16:03:03

标签: c scanf

这是一个“有效”的程序,但如果输入字符数据“a”或输入“-8”,它将进入无限循环。

以下是将数据输入程序时的预期输出:

****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;
}

感谢。总计新闻和感谢帮助。

1 个答案:

答案 0 :(得分:-1)

检查scanf的返回值,并在非法输入的情况下清除输入缓冲区。

像这样:

#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;
}