c - 在 C 中验证整数

标签 c validation input integer validating

我正在用 C 创建一个程序,我必须接受一个整数才能继续。我阅读了一些问题以使用以下代码,但我的程序在输入任何字符后很快就进入无限循环。请帮助我

    int tnum,scancheck;
printf("Enter the number of teams(Maximum 4)\n");
scancheck = scanf("%d",&tnum);
while(scancheck != 1)
{
    printf("ERROR: Please enter numbers only\n\n");
    printf("Enter the number of teams(Maximum 4)\n");
    scancheck = scanf("%d",&tnum);  
}

我使用了基里连科的方法,但我的程序在输入特殊字符(例如l=)时进入无限循环

编辑 问题已解决。谢谢大家

最佳答案

您必须在调用 scanf 之间清理 stdin。否则,具有无效输入的 scanf 的行为是将字符放回流中。然后,它进入无限循环,每次迭代都会读取相同的错误字符。

#include <stdio.h>

void clean_stdin(void) {
    int c;
    while ((c = getchar()) != '\n' && c != EOF)
        ;
}

/* ... */

int ret;
int n;

do {
   ret = scanf("%d", &n);
   clean_stdin();
} while (ret != 1);

关于c - 在 C 中验证整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12978647/

相关文章:

c - 使用 typedef 结构时出现未知类型错误

javascript - 如何使用自定义模板在 Angular 中正式设置 modelValue

javascript - Jquery Validation Unvalidated form submit button can be clicked (With Fiddle)

jquery - 单击复选框时向父元素添加/删除类

list - 将数字输入到空列表 Python

c - Struct inside union, 串口状态

c - 在实时视频流中跟踪和替换标记

c - 作为参数传递的复合文字的生命周期是多少?

json - PostgreSQL : Is there a way to select all valid json data type

javascript - fileReader Javascript 的结果并不总是相同