繁体   English   中英

从C中的stdin读取数字

[英]Reading a number from stdin in C

我有一个从C中的stdin获取数字的功能。

int io_get_num(const char *q, const size_t min, const size_t max, int * num)
{ /* Get a number from the command line */
    int ret = 0;

    do {
        printf(q);
        ret = scanf(" %d", num);
        if (ret == EOF)
            return EOF;
        else if (ret == 0)
            printf("Please provide a valid number ..\n%s", q);
        else if (*num > max || *num < min)
            printf("Number must be smaller than %u and larger than %u\n%s", (unsigned int)max+1, (unsigned int)min-1, q);
        else
            break;
        /* Flushing stdin */
        int ch;
        while ( (ch = fgetc(stdin)) != EOF && ch != '\n' );
    } while (1);

    return ret;
}

它在第一次循环运行中运行良好,然后(我注意到在使用gdb中断时)循环运行两次,除了它不等待我的输入或检查任何条件(这可能与刷新流有关) ..

我该怎么办?

由于某种原因,您每次重复打印q两次:一次在开始,然后在错误消息之后再次。 这可能会对每个输入重复两次的循环产生一种错觉,但实际上并没有发生。 在我的实验中,我无法重现这种双重重复。

此外,空间之前%dscanf(" %d", num)是多余的。 这不是错误,它将使scanf跳过任何前导空格,但是%d本身已经在内部跳过了前导空格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM