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

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

本文介绍了检测是否仅给出整数的程序进入无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This program to detect whether only integer has been given or not goes into infinite loop when invalid data is entered instead of asking for new valueswhy doesn't the goto work here?

推荐答案

scanf()可以返回不同于2的值的原因有很多:

There are multiple reasons scanf() can return a value different from 2:

  • 存在无法根据转换规范转换的待处理输入.例如,如果输入流中有一个A待处理,则%d转换失败,并且A保留在输入流中.您的代码只会继续尝试进行此转换,并且永远不会停止.重试之前,您应该阅读并丢弃有问题的输入.
  • 输入流发生读取错误或到达文件末尾.如果至少一次转换成功,则返回成功转换的次数,否则返回EOF.如果返回EOF,则没有任何必要再次尝试,因为没有更多输入可用.
  • 还请注意,对于使用whilefor之类的流控制语句更好地表达的构造,使用goto被认为是不好的风格.
  • there is pending input that cannot be converted according to the conversion specification. For example if there is an A pending in the input stream, the %d conversion fails and the A stays in the input stream. Your code just keeps trying this conversion and will never stop. You should read and discard the offending input before re-trying.
  • the input stream has had a read error or hit the end of file. If at least one conversion succeeded, the number of successful conversions is returned, otherwise EOF is returned. If EOF is returned, there is no point trying again since no more input will be available.
  • Note also that it is considered bad style to use goto for constructions that are better expressed with flow control statements such as while and for.

这是更正的版本:

#include <stdio.h>

// program to detect whether only integer has been given or not
int main() {
    int a, b, s, c;

    printf("Enter two proper numbers: ");
    for (;;) {
        s = scanf("%d%d", &a, &b); //storing the scanf return value in s
        if (s == 2) // conversions successful
            break;
        if (s == EOF) {
            printf("unexpected end of file\n");
            return 1;
        }
        /* discard the rest of the input line */
        while ((c = getchar()) != EOF && c != '\n')
            continue;
        printf("Invalid input. Try again: ");
    }
    printf("The values are %d and %d\n", a, b);
    return 0;
}

这篇关于检测是否仅给出整数的程序进入无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 15:00