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

标签 c arrays terminal counter

程序会不断地将数字扫描到一个数组中,该数组不超过 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 时,它会生成文件结尾或关闭输入流。即使到达文件结尾(如果未显式处理),while 循环也会运行到 i<=98 。当使用 ctrl+d 关闭输入流时,scanf 在尝试读取时返回 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 生成的]

关于c - 如何在使用 CTRL-D 退出时让 while 循环中的计数器停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58265316/

相关文章:

c - 为什么程序返回的退出代码不是我指定的?

CreateProcess 和 lpCommandLine 生命周期

arrays - 使用 MongoDB 更新对象的属性而不删除周围的属性

c - 返回二维数组或指向一个的指针

linux - 即时解压缩和压缩为另一种格式

docker - 在Mac OS X上通过 `-it`命令提取图像后如何进入docker容器?

visual-studio-code - 如何在 VS Code 终端中突出显示要复制和粘贴的文本?

C++:一般来说,我应该使用字符串还是字符数组?

javascript - 如何使用 typescript 向数组添加额外的属性

c - 添加额外的 'int' 关键字时,while 循环不会中断?