c - scanf 函数无限接受值

标签 c scanf infinite-loop


int n;
int a[maxsize];
int b[maxsize];
int c[maxsize];
int i;
printf("enter number of  elements(disks)\n");
scanf("%d",&n);
printf("enter the elements in ascending  order\n");
for(i=0;i<n;i++)
{   
    scanf("%d",&a[i]);
}

这有时工作正常,但大多数时候这段代码进入无限循环,循环中的'scanf'无限接受值,我尝试使用函数(fflush)清除缓冲区内容,但仍然无法正常工作,有人请帮帮我!!并请解释原因!!

最佳答案

发布的代码不能进入无限循环,很可能是 scanf() 函数阻塞,直到您输入类似 Ctrl+D 的内容结束输入流或者可能是另一个整数,问题是你正在以一种非常危险的方式处理输入,因为你根本没有检查错误,这可能会做你真正想要的事情

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

#define clearstdin() do {int chr; while (((chr = getchar()) != EOF) && (chr != '\n')); } while (0)
#define SOMELARGESIZE 1024

int main(void)
{
    unsigned int index;
    unsigned int size;
    int          result;

    fprintf(stderr, "input the desired array size: ");
    while (((result = scanf("%u", &size)) != 1) && (result != EOF))
     {
        fprintf(stderr, "invalid input, try again\n");
        clearstdin();
     }
    if (result == EOF)
     {
        fprintf(stderr, "EOF recieved, ending the program\n");
        return -1;
     }
    if (size < SOMELARGESIZE)
     {
        int array[size];

        for (index = 0 ; index < size ; index++)
         {
            fprintf(stderr, "input an integer: ");
            if (((result = scanf("%d", &array[index])) == 1) && (result != EOF))
                fprintf(stdout, "\tarray[%d] = %d\n", index, array[index]);
            else if (result == EOF)
             {
                fprintf(stderr, "EOF recieved, ending the program\n");
                return -1;
             }
            else
             {
                fprintf(stderr, "invalid input, try again\n");
                index -= 1;
             }
            clearstdin();
         }
     }
    else
     {
        fprintf(stderr, "sorry, you requested a very large array\n");
        return -1;
     }
    return 0;
}

上面程序的唯一问题是,如果您在 scanf() 等待输入时输入任何空白字符,它将什么都不做,直到输入有效或无效但特别是非白色-输入空格。

关于c - scanf 函数无限接受值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29321822/

相关文章:

java - Try-catch 创建无限循环

wcf - 通过WCF的 Entity Framework 导航属性循环问题

c - 如何在函数外使用 for 循环创建多个全局变量?

c - 同一程序的不同启动过程中的多个(随机选择)输出。 fscanf'ing 时添加的随机字符

c - C 中的 fscanf 带有一个没有空格的文本文件

java - 防崩溃扫描仪--无限循环错误(开始java)

c - 如何使用 C 发送和捕获发送到 PID 的信号

c - 指针数组更改值,使用 malloc 将内存分配给其他指针时

c++ - 如何让 GDB 在每次系统或库函数调用时中断?

C编程: Input is assigned but output display shows the incorrect value