首页 > 解决方案 > 检测是否只给出整数的程序进入无限循环

问题描述

// program to detect whether only integer has been given or not
int main() {
    int a, b, s; 
    printf("Enter two proper number\n");
 BEGIN:
    s = scanf("%d %d", &a, &b); //storing the scanf return value in s
    if (s != 2) {
        printf("enter proper value\n");
        goto BEGIN;
    }
    printf("The values are %d and %d ", a, b);
}

当输入无效数据而不是询问新值时,这个检测是否只给出整数的程序进入无限循环为什么在goto这里不起作用?

标签: cscanfgoto

解决方案


请注意,当scanf输入错误(例如您输入cat dog)时,该输入将保留在输入缓冲区中,直到您采取措施将其清除。所以循环不断重复并拒绝仍然存在的相同输入。

它使用起来更简单fgetssscanf如果扫描失败,您只需忘记输入字符串并获取另一个字符串。

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

int main(void) {
    int a, b;
    char str[42];
    do {
        printf("Enter 2 numeric values\n");
        if(fgets(str, sizeof str, stdin) == NULL) {
            exit(1);
        }
    } while(sscanf(str, "%d%d", &a, &b) != 2);
    printf("Numbers are %d and %d\n", a, b);
}

节目环节:

输入 2 个数值
猫狗
输入 2 个数值
猫 43
输入 2 个数值
42 狗
输入 2 个数值
42 43
数字是 42 和 43

请注意,这goto是 C 语言中不好的做法,仅应在没有其他方式构建代码的情况下使用——通常有这种方式。


推荐阅读