Skip to main content
 首页 » 编程设计

c中检测是否只给出整数的程序是否进入无限循环

2025年12月25日120zlslch

// 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在这里不起作用?

请您参考如下方法:

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

使用 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); 
} 

节目环节:

Enter 2 numeric values 
cat dog 
Enter 2 numeric values 
cat 43 
Enter 2 numeric values 
42 dog 
Enter 2 numeric values 
42 43 
Numbers are 42 and 43 

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