Scanf意外返回EOF

我的代码有什么问题? 输入以下内容(通过文件)时:

6.02
110 223 144 208 199.5 890
200 69.5 300 138.7 190 601

它会打印ERROR: invalid price in airline # 1,但不应打印。 这是我的代码。

int fillPricesTable(double flightsPrices[][DEST],int n,double* dollarRate)
{
    //n is the number of rows
    double Price;
    int  AirLinesCounter=0;
    while (scanf("%lf",dollarRate)==EOF || *dollarRate<=0)
    {
        errorDollar();
        fflush(stdin);
    }
    for (int i=0;i<n;++i)
    {
        for (int j=0;j<6;++j)
        {
            if (scanf("%lf",&Price)==EOF || Price<=0)
            {
                printf("ERROR: invalid price in airline # %d\n",i);
                return -1;
            }
            flightsPrices[i][j]=Price;
        }
        AirLinesCounter++;
        if(scanf("%lf",&Price)==EOF)
            break;
    }
    return AirLinesCounter;
}
lengci 回答:Scanf意外返回EOF

由于if(scanf("%lf",&Price)==EOF)循环主体之后的for (int j=0;j<6;++j)AirLinesCounter++之后的那个),您在i的每个循环中扫描的数字太多了。 / p>

只需将第二个if与身体移开即可。

fflush(stdin);在技术上是未定义的行为。要从输入中读取缓冲的数据,请循环getchar()直到换行符或EOF。

例如,您可以删除第二个条件,例如在错误中添加一个条件,以处理分别扫描该行中第一个数字的错误:

int fillPricesTable(double flightsPrices[][DEST],int n,double *dollarRate)
{
    while (scanf("%lf",dollarRate) != 1 || *dollarRate <= 0) {
        errorDollar();
        for (int i; (i = getchar()) != '\n' && i != EOF;);
    }

    bool end_me = false;
    int i = 0;
    for (i = 0; i < n && end_me == false; ++i) {
        for (int j = 0; j < 6; ++j) {
            // no need to scan into temporary variable
            // just scan into the destination
            if (scanf("%lf",&flightsPrices[i][j]) != 1 || flightsPrices[i][j] <= 0)  {
                if (j == 0) {
                    // this is first number in the row
                    end_me = true; // using separate variable to end the outer loop
                    // because C does not have "break 2" or similar.
                    break;
                } else {
                    errorPrice(i);
                    return -1;
                }
            }
        }
    }
    return i; // AirLinesCounter is equal to i....
}
本文链接:https://www.f2er.com/2829975.html

大家都在问