如何在 while 循环中重新提示

How to reprompt in a while loop

 while(1)
{
     printf("Please enter the first number:\n");
     if(scanf(" %f",&num1))
       break;
}

我正在尝试在用户输入字符时重新提示他们输入整数值。 当我 运行 这段代码创建了一个无限循环。我用的是c语言

#include <stdio.h>  

int clean_stdin()
{
    while (getchar()!='\n');
    return 1;
}

int main(void)  
{ 
    int num1=0;  
    do
    {  
        printf("\nPlease enter the first number: ");
    } while ((scanf("%d", &num1)!=1 && clean_stdin()));

    return 0;  
}

说明

只有当输入的值为包含非数字字符的字符串时,才会执行clean_stdin()函数。并且总是returnTrue,也就是说输入的值肯定是一个数值。

有关更多信息,请参阅这个惊人的 answer