为什么EOF在我的scanf while循环期间没有终止?

时间:2018-08-21 19:31:19

标签: c++

我刚刚开始学习C ++,正在尝试学习如何使用scanf和printf获得更快的输入和输出。这是我目前正在处理的代码:

#include <stdio.h>
using namespace std;

int main() {
    int time, record;
    double down, loan;
    while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) != EOF) {
        double value = down + loan;
        double owed = loan;
        double payment = owed/time;

        // current simulated month and depreciation
        int rday, c = 0;
        double temp, dep;
        bool found = false;

        // finds value and owed after records
        while (!found && record > 0) {
            scanf("%d %lf", &rday, &temp);
            // adjusts value and owed to day before listed on record
            while (!found && c <= rday) {
                if (c == rday) {
                    dep = temp;
                }
                value *= 1 - dep;
                if (c > 0) {
                    owed -= payment;
                }
                c++;

                // determines if found date
                if  (owed < value) {
                    found = true;
                }
            }
            record--;
        }

        // finds point where owed < value
        while (!found && value < owed) {
            value *= 1 - dep;
            owed -= payment;
            c++;
        }

        if (c - 1 == 1) {
            printf("%d month\n", c - 1);
        }
        else {
            printf("%d months\n", c - 1);
        }
    }
    return 0;
}

当我在Code :: Blocks上运行此命令时,它会打印正确的答案,但是即使输入CTRL+Z(我使用Windows),最外面的while循环也不会终止。这是我的输入:

30 500.0 15000.0 3
0 .10
1 .03
3 .002
12 500.0 9999.99 2
0 .05
2 .1
60 2400.0 30000.0 3
0 .2
1 .05
12 .025
-99 0 17000 1

以下是发生的情况的图像:

Error

我尝试将循环条件更改为scanf("%d %lf %lf %d", &time, &down, &loan, &record) == 4,但是发生相同的问题。有人可以解释一下我的代码的问题是什么吗?

3 个答案:

答案 0 :(得分:2)

在线

while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) != EOF)

您希望读取成功时将读取4个变量。当scanf能够成功地从stdin中提取所有参数的数据时,它将返回4。将支票更改为使用该数字。

while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) == 4)

答案 1 :(得分:0)

这是因为scanf从不返回EOF,所以永不满足终止条件。

答案 2 :(得分:0)

谢谢大家的建议和回答!我发现了这个错误。有点尴尬,但事实证明问题出在最后一行输入上。