首页 > 解决方案 > 如何轻松检查输入是否为 char 而不是运行它?

问题描述

这段代码几乎按照我喜欢的方式运行,但唯一的问题是当我使用 char 作为输入时,它会进入无限循环。我怎样才能解决这个问题?

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

int main(){

    int year;
    int age;

    printf("This program will calculate how old you are \n\n");
    //sleep(2); 
    do
    {
        printf("what year are you born in?\n");
        scanf("%d", &year);
        age = 2020 - year;
      
        if(year >= 1910 && year <= 2020){
            printf("You will or have turned %d year this year \n\n", age);
            //sleep(1);
        }else if (year == 0){
            printf("Program exits \n");
        }else{
            printf("write a valid input between 1910 and 2020\n\n");
        }
    }while (year != 0);

    //system("PAUSE");
    return 0;
}

标签: c

解决方案


推荐阅读