scanf()也有返回值,输入正确时,返回正确读入的参数个数,且为int 型;无参数正确读入或文件末尾错误,返回0或EOF;
利用其返回值判断输入是否为int,若输入为字母、小数或其他特殊符号退出循环,代码如下:
int main(void)
{
int status, num = 1;
printf(" Please input a integer number: \n ");
status = scanf("%d", &num);
while(status == 1)
{
printf(" num = %d \n ",num);
printf(" Please input another integer number: \n ");
status = scanf("%d", &num);
}
printf("Done!\n");
return 0;
}
以上代码只能判断输入为int型,可通过添加判断语句限制输入为正整数;
while(status == 1 && num > 0)