如何在C中显示消息或响应无效输入

时间:2015-09-17 07:22:45

标签: c

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main()
{
    int a, result;
    float b;
    printf("**This is a simple arithmetic calculator.** \n");
    printf("\n Please enter an integer: ");
    scanf("%i ", a);
    printf("Please enter a floating point number: ");
    scanf("%f", b);

    result = a + b

    printf("Output: ");
    printf("%i + %f = %lf \n", a, b, result);
    printf("%i - %f = %lf \n", a, b, result);
    printf("%i * %f = %lf \n", a, b, result);
}

如果用户输入无效输入,我需要确保您的程序不会崩溃。

2 个答案:

答案 0 :(得分:3)

scanf是一个函数,它还有一个返回值,表示正确插入了多少输入。 所以你可以这样做:

while (scanf("%i ", a) != 1)
{
   printf("wrong input, try again");
}

答案 1 :(得分:0)

使用while循环或if for scanf

while(scanf("%i ", a) !=1){
    printf("invalid input.\n");
}

while(scanf("%f", b) !=1){
    printf("invalid input.\n");
}