【问题标题】:How to have a counter in a while loop stop when exiting with CTRL-D使用CTRL-D退出时如何在while循环中停止计数器
【发布时间】:2019-10-07 07:41:33
【问题描述】:

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

【问题讨论】:

  • 提示:看看scanf的返回值,看看你是否可以改变你的第一个while循环的条件来利用它。
  • 调用scanf时,总是检查它的返回值。如果您尝试匹配一个输入,而 scanf 没有报告它已匹配 1 个输入,则出现问题。

标签: c arrays terminal counter


【解决方案1】:

当按下 ctrl+d 时,它会生成文件结尾或关闭输入流。即使到达文件结尾,如果未明确处理,while 循环将一直运行到i&lt;=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生成]

【讨论】:

  • 检查scanf 的返回值很重要,是的,EOF 是 OP 询问的条件——但是像这样测试 EOF 也很差。特别是,在其中任何位置包含单个 x 字符的输入上尝试此代码。
  • 我假设您的输入将只包含整数。如果输入中给出了除 intger 以外的任何内容,您是否要停止循环?如果是,则编辑后的内容应该适用于任何输入字符或 ctrl+d
  • @Reshad 它的意思是用你输入的 scanf 的数量填充一个数组。所以如果我输入 10 20 30 40 50,数组应该只包含这些数字。我不知道该怎么做。
【解决方案2】:

在研究了scanf 如何返回值,以及对类似项目的其他研究之后,这段代码完美地按照预期运行。 感谢您指出 scanf 返回值以及如何使用它们!

#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;
}

帮助这个项目的帖子是here!

【讨论】:

    猜你喜欢
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2018-10-09
    • 1970-01-01
    • 2015-07-30
    • 2012-04-28
    • 1970-01-01
    相关资源
    最近更新 更多