繁体   English   中英

奇怪的循环而 scanf

[英]Weird Loop While scanf

我写了这段代码。 它必须读取一个 1 到 4 之间的整数(定义为函数的下限和上限),如果条件失败,则打印一些错误消息并再次提问。

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

int varcheck(double x, char z, int lowerbound, int upperbound);

int main(){

    double playerCount;
    char i;

    printf("Insert Number of Players: ");
    scanf("%lf%c", &playerCount, &i);

    while(varcheck(playerCount, i, 1, 4) == 0){
        printf("Invalid Number of Players\n");
        printf("Insert Number of Players: ");
        scanf("%lf%c", &playerCount, &i);
    } 
    // ...Code continues...
}




int varcheck(double x, char z, int lowerbound, int upperbound){
    double r = 0;
    r = x - (int)x;  /*If r == 0 then its not decimal number*/ 

    if(r != 0 || z != '\n' || x < lowerbound || x > upperbound){
        return 0;
    } else {
        return 1;
    }
}

函数进入一些奇怪的循环,谁能帮我解决这个问题?

嗯,首先,这段代码完全是一团糟。

  1. 您尚未终止任何引用的部分(在printf s 和scanf s 中)
  2. 无缩进
  3. playerCount使用double
  4. 由于它是double ,它的值可能类似于12.000001 ,因此r可能永远不会是0
  5. 当您必须分析像\\t\\n和 " 这样的字符时,我建议使用getchar而不是scanf “ (空间)。
  6. 我会说再次检查这一部分: x < lowerbound || x > upperbound x < lowerbound || x > upperbound因为我认为您打算这样做: x > lowerbound || x < upperbound x > lowerbound || x < upperbound

解决这些问题,我猜您的代码应该可以正常工作。 缩进与准确性无关。

函数scanf用于解析用户输入有点困难。 一个问题是,如果scanf无法解析您询问的对象,则scanf会使输入流保持完整/不变。 示例 - 如果您输入“aaa2”并尝试扫描浮点scanf会给您零结果并且输入流仍将保留“aaa2”。 因此,下一个scanf也会看到数据“aaa2”,并且你有一个无限循环。

解决方案是在转换失败时刷新输入流。 那可能是这样的:

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

void flushInput()
{
    // Keep reading from input stream until a newline is read
    int c;
    do
    {
        if ((c = getchar()) == EOF) exit(1);
    } while (c != '\n');
}

int getInt()
{
    int n;
    char c;
    while(1)
    {
        // scanf will return 2 if the conversion is succesful, i.e.
        // if it could scan first an integer and then a character
        if (scanf("%d%c", &n, &c) == 2 && c == '\n') return n;

        // Conversion failed so flush the input stream
        flushInput();
    }
}

int main(void) {
    int n;
    int lowerbound = 1;
    int upperbound = 4;
    do
    {
        n = getInt();
    } while (n < lowerbound || n > upperbound);
    printf("n=%d\n", n);
    return 0;
}

输入:

4.2

aaaa2
9
3a
2

输出:

n=2

暂无
暂无

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

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