我正在学习 C,现在我想从键盘获取输入(2 个数字范围 [0,99] 并比较它们)。我发现了很多获取输入的选项:
- 扫描函数()
- 获取字符()
- fgets()
- 获取()
我尝试了其中一些:
扫描:
#include<stdio.h>
main()
{
int flag=0,num1, num2;
printf("Give a number between 0-999");
do{
if(flag == 1){
printf("Wrong Input. Plz give a number between 0-99 ");
}
printf("\nnumber 1: ");
scanf("%d", &num1);
flag=1;
}while(num1<0 || num1>1000);
printf("Give one more");
flag=0;
do{
if(flag == 1){
printf("Wrong Input. Plz give a number between 0-99 ");
}
printf("\nnumber 2: ");
scanf("%d", &num2);
flag=1;
}while(num2<0 || num2>1000);
if(num1>num2){
printf("the max number is : %d\n", num1);
}else
if (num1<num2){
printf("the max number is : %d\n", num2);
}else
printf("they are equals\n");
}
但是,如果我按 a 不是数字,它会无限打印:
数字 2:输入错误。请给出 0-99 之间的
数字 2:输入错误。请给出 0-99 之间的
数字 2:输入错误。请给一个 0-99 之间的数字
// 然后继续..
然后我尝试使用getchar:
#include<stdio.h>
main()
{
int flag=0;
char input1,input2;
printf("Give a number between 0-999");
do{
if(flag == 1){
printf("Wrong Input. Plz give a number between 0-99 ");
}
printf("\nnumber 1: ");
input1 = getchar();
flag=1;
}while(input1<0 || input1>1000);
printf("Give one more");
flag=0;
do{
if(flag == 1){
printf("Wrong Input. Plz give a number between 0-99 ");
}
printf("\nnumber 2: ");
input1 = getchar();
flag=1;
}while(input2<0 || input2>1000);
if(input1>input2){
printf("the max number is : %c\n", input1);
}else
if (input1<input2){
printf("the max number is : %c\n", input2);
}else
printf("they are equals\n");
}
但这段代码不起作用。有什么建议么?