C程序使用scanf进入无限循环

标签 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;
}

谢谢。完全新手,感谢您的帮助。

最佳答案

检查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;
}

关于C程序使用scanf进入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46159868/

相关文章:

检查文件中的重复单词

c - C 编程中 "&"%f", &variableName);"中的 "scanf("是什么?

c - 使用 fscanf() 读取多个值(如下面的文本文件所示)

python - int 到字符串连接

c - C 中的二维数组搜索

C - 重新声明变量时出错

c - 默认情况下,读取输入缓冲区中的哪个字符会使 scanf() 停止读取字符串?

c - 如何只使用2个引脚而不影响其他引脚?

Control-D 结束 getchar 而不是程序,prog 继续接收变量中的垃圾值?

c++ - 不明白 sscanf() 函数是如何工作的