c - C中的无限while循环不等待再次扫描数据

标签 c

#include <stdio.h>

int main() {
    int i;
    while (1) {
        printf("Enter no?\n"); // step -1

        if (scanf(" %d", &i) > 0)   // step-2
            printf("Num=%d\n", i);
        else
            printf("Entered character.Pls enter int\n");
    }
}

当我使用字符输入运行上述代码时,如果用户输入了整数以外的值,我想再次继续扫描,它正在运行无限循环。请提出原因或任何解决方案...?

最佳答案

#include <stdio.h>

int main() {
    int i;
    while (1) {
        printf("Enter no?\n"); // step -1

        if (scanf_s(" %d", &i) > 0) {   // step-2
            printf("Num=%d\n", i);
            break;
        }
        else {
            printf("Entered character.Pls enter int\n");
            fseek(stdin, 0, SEEK_END);
        }
    }
}

关于c - C中的无限while循环不等待再次扫描数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42068025/

相关文章:

c - 构建一个使用 c 代码库的 R 包

c - 你如何使用正则表达式捕获一个组?

c - sscanf 返回正确数量的参数,即使最后一个输入错误

有符号的 long long 可以用作 OpenMP 中的迭代变量吗?

windows-server-2008-r2 - 使用 GetOpenFileName 时 C 应用程序崩溃。 DEP 阻止了崩溃

c - 有没有办法在 GCC 中编译程序而无需汇编?

c - 使用 GCC 的另一个目录中的静态库和 header

python - 如何在 C 程序中运行 Python 可执行文件(.py)(例如使用 execvp)?

自定义 linux pcie 驱动程序 MSI 中断

c - 变量定义和地址