c - scanf 跳过一行

标签 c arrays loops printf scanf

我正在编写一个代码,提示用户输入他们选择的几天(3 到 10 天)的高点和低点。到目前为止,除了用于输入高温和低温的 scanf 函数出现比应有的低一行之外,一切正常。例如,第 1 天的最高价和最低价将被输出,但用户的输入从第 1 天的最低价开始,因此高价的输入紧挨着低价,低价的输入在下一个空白行。

我认为问题可能是 printf 在 scanf 生效之前完成了输出高和低的功能。有没有办法让 scanf 发生,以便可以将高值和低值并排输入?这是我的代码:

#include <stdio.h>

int main (void)
{
    int i;
    int limit;
    int day[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int high[10],low[10];

    printf("---===IPC Temperature Analyzer V2.0===---\n");

    printf("Please enter the number of days between 3 and 10, inclusive: ");
    scanf("%d", &limit);
    while (limit <= 2 || limit >= 11) {
            printf("Invalid");
            scanf("%d", &limit);
    }

    for(i = 0;i < limit; i++) {
            printf("Day %d - High:\n Day %d - Low: ",day[i],day[i]);
            scanf("%d%d", &high[i], &low[i]);
    }

    return 0;
}

最佳答案

你在找这样的东西吗?

for(i = 0;i < limit; i++) {
    printf("Day %d - High: ", day[i]);
    scanf("%d", &high[i]);
    printf("Day %d - Low: ", day[i]);
    scanf("%d", &low[i]);
}

这导致:

Please enter the number of days between 3 and 10, inclusive: 4
Day 1 - High: 5
Day 1 - Low: 3
Day 2 - High: 4
Day 2 - Low: 2
Day 3 - High: 2
Day 3 - Low: 1
Day 4 - High: 5
Day 4 - Low: 9

关于c - scanf 跳过一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42182779/

相关文章:

c - 从 void* 变量推断类型

在 C 中的 for 循环中创建多个 pthread

c - 在c中传递数组元素指针

mysql - Node.js 在循环中与 MySQL 链接 promise

c++ - 如何从循环中写入多个输出?

c - 函数总是分配到相同的地址,并且变量不会改变

c - 如何用 C 语言计算计算机的字长?

arrays - 如何在 perl 中查找数组元素内的所有匹配项并从每个匹配项创建一个新元素?

java - 将 LongBuffer/IntBuffer/ShortBuffer 转换为 ByteBuffer

c++ - 我的循环不会循环