使用 CTRL-D 退出时如何让 while 循环中的计数器停止

How to have a counter in a while loop stop when exiting with CTRL-D

程序会不断扫描数字到一个数组中,数组不会大于100个值。

然而,尽管程序在输入第三个值后退出,但第一个 while 循环中的计数器 'i' 继续计数到 99。因此,当启动第二个 while 循环时,它会打印从 99 开始的值。

如何在退出循环时让计数器停止?

这是作业,也是第一次接触C语言的数组

我已经尝试过使用 if 语句排除所有不必要的数组值的零,但有时 0 可以输入数组并需要打印。

#include <stdio.h>

int main(void) {

    printf("Enter numbers forwards:\n");
    int numbers[99] = {0};

    // Components of the scanning while loop
    int i = 0;
    while (i <= 98) {
        scanf("%d", &numbers[i]);
        i = i + 1;
    }

    // Components of while loop
    int counter = i - 1;

    printf("Reversed:\n");

    while (counter >= 0) {
        printf("%d\n", numbers[counter]);
        counter--;
        /*if (numbers[counter] == 0) {
            counter--;
        } else {
            printf("%d\n", numbers[counter]);
            counter--;
        }*/
}

预期结果向前输入号码: 10 20 30 40 50 CTRL-D 反转: 50 40 30 20 10

实际结果向前输入号码: 10 20 30 40 50 CTRL-D 反转: 0 0 0 ... 50 40 30 20 10

当按下 ctrl+d 时,它会生成一个文件结尾,或者它会关闭输入 stream.even 如果到达文件结尾,如果没有明确处理 while 循环将 运行 直到i<=98。当使用 ctrl+d 关闭输入流时,scanf returns 尝试读取时的 EOF 标志。

为了实现您的目标,您必须像这样编写 while 循环:

while (i <= 98) {
    if(scanf("%d", &numbers[i])<=0)
        break;
    i = i + 1;
}

// Components of while loop

[ 请记住文件末尾是在 windows 中使用 ctrl+z 和在 linux 中使用 ctrl+d ]

在研究了 scanf return 的价值观以及对类似项目的其他研究后,这段代码完美地实现了它的预期。 感谢您指出 scanf return 值以及如何使用它们!

#include <stdio.h>

int main(void) {

    printf("Enter numbers forwards:\n");

    int userInteger = 0;
    int i = 0;
    int numbers[100] = {0};

    // As suggested, if the user inputs 1 integer into scanf, it will return 1
    // Therefore, as long as integers are being read into the program, the 
    // while loop will continue to run. It will stop when a non-integer is 
    // input.
    // When hitting CTRL-D, this will stop the loop here and stop the counter
    while (scanf("%d", &userInteger) == 1) {
        numbers[i] = userInteger;
        i++;
    } 

    printf("Reversed:\n");

    // Due to the final i being counted in the previous
    // loop before failure
    i = i - 1; 

    while (i >= 0) {
        printf("%d\n", numbers[i]);
        i--;
    }
    return 0;
}

对这个项目有帮助的 post 是