c - Scanf 意外返回 EOF

标签 c scanf c99 eof io-redirection

我的代码有什么问题吗? 当给出以下输入时(通过文件):

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

它会打印ERROR: invalid Price in Airlines # 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;
}

最佳答案

因为if(scanf("%lf",&Price)==EOF) for (int j=0;j<6;++j)正文之后循环( AirLinesCounter++ 之后的那个),您在 i 上的每个循环中扫描过多的一个数字.

只需删除第二个 if与 body 。

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

例如,您可以删除第二个 if,并在错误中添加一个条件来处理单独扫描行中第一个数字的错误:

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....
}

关于c - Scanf 意外返回 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59564899/

相关文章:

将 C dll 头文件转换为 Delphi Pascal 头文件

Web服务器在C中接收GET请求的配置文件

C:扫描期间的动态分配

使用 MinGW 将旧的 C99 程序转换为 C11

C99 临时局部数组变量的 C++ 版本

c - 为什么 valgrind 仅通过多次运行程序就报告不同的结果(不可能/仍然可以到达泄漏)?

c - C 中的信号和回调?

c - 为什么 scanf 不能在正式输入末尾使用空格?

我可以在 C 中同时扫描和打印整数吗?

c - LLVM 编译器 2.0 错误?