c - do-while循环不断重复

标签 c

你能告诉我为什么这个循环一直重复而不让我阅读 n 吗?

int n;
do
{
    printf("Height: ");
    scanf("%d",&n);
}
while(n < 0 || n > 23);

我无法输入任何值,因为“高度:”一直在重复。这是完整的代码:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n,i,j,k;
    do
    {
        printf("Height: ");
        scanf("%d",&n);
    }
    while(n < 0 || n > 23);

    for(i=0;i < n;i++)
    {
        for(j=0;j < n - i - 1;j++)
        {
            printf("%c",' ');
        }
        for(k=0;k < i + 2;k++)
        {
            printf("%c",'#');
        }
        printf("\n");
    }
}

最佳答案

检查scanf的返回。在这种情况下,如果 scanf 成功,它将返回 1。如果它不返回 1,则输入无效,例如 www 为 int。在这种情况下,请清除缓冲区并重试。

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

int main()
{
    int i = -1;

    do {
        printf ( "height \n");
        if ( scanf ( "%d", &i) != 1) {// != 1 means scanf failed
            while ( ( i = getchar()) != '\n' && i != EOF) {
                ;//clear buffer
            }
            i = -1;
        }
    } while ( i < 0 || i > 23);

    return 0;
}

关于c - do-while循环不断重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32512851/

相关文章:

当 fork() 遇到 fopen() 时的困惑

c++ - 如何从将波兰表示法转换为反向波兰表示法的递归函数返回指针?

c - 这个将 char 数组转换为 int 数组的函数不起作用吗?

c - 将结构数组传递给函数

c - _Atomic 类型限定符和类型说明符之间有区别吗?

c - 为什么我收到 'Incompatible pointer type' 警告?

c - hlist_for_each_entry_rcu 是否需要向其中传递额外的指针?

python - 如何在 Python 中使用 librt 函数?

c - Ntp 服务器没有响应我的客户端

c - 使用列表,将数字按升序排列