程序会不断地将数字扫描到一个数组中,该数组不超过 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/