【问题标题】:3rd and 4th scanf not taking input第三和第四个 scanf 不接受输入
【发布时间】:2015-12-03 19:37:18
【问题描述】:

我正在尝试通过scanf() 将输入输入到数组中。第一次和第二次scanf() 电话似乎按我的预期工作。其他两个不起作用,我不知道为什么。谁能指出问题所在?

这是我的代码:

#include <stdio.h>

#define SIZE_A (10)
#define SIZE_B (10)
#define SIZE_C (SIZE_A+SIZE_B)

int main()
{
    int A[SIZE_A] = {0}, B[SIZE_B] = {0};
    int A_input = 0, B_input = 0;

    printf("First series length:\n");
    scanf("%d", &A_input);
    printf("Enter %d numbers for first series:\n", A_input);
    scanf("%d %d %d %d %d %d %d %d %d %d", &A[0], &A[1], &A[2], &A[3], &A[4],
            &A[5], &A[6], &A[7], &A[8], &A[9]);
    {
        printf("Second series length:\n");
        scanf("%d",&B_input); /* problem here */
        printf("Enter %d numbers for second series:\n", B_input);
        scanf("%d %d %d %d %d %d %d %d %d %d", &B[0], &B[1], &B[2], &B[3], &B[4],
                &B[5], &B[6], &B[7], &B[8], &B[9]); /* problem here */
    }

    return 0;
}

【问题讨论】:

  • Err...为什么你问了这个系列的长度,然后完全忽略了它们?您不能丢弃任何未使用的条目字段,直到您输入 10 个值才能满足第一个系列条目。在说 5 个条目后点击 enter 并认为代码将进入第二个系列是没有用的。 enter 只是空格,space 也是如此。
  • 起初,我以为我会使用它们来确定数组大小,但我看到它必须是 const 稍后将在其余代码中使用它
  • 请更具体地描述您的程序的行为,而不是“它不起作用”。具体来说,确切的输入是什么?对于这些输入,您的程序观察到的行为是什么?
  • 使用序列长度进行循环,每次迭代都要求一个值。并检查来自scanf() 的返回值。并检查每个系列的长度是&lt;= 10。您是唯一可以保护您自己的 C 代码的人。
  • 正如@WeatherVane 所说,除非您在每个系列中恰好提供十个数字,否则该程序将无法按您的意愿运行。如果这不能解释问题,那么请提供您正在使用的输入、您得到的结果以及您认为不正确的原因。

标签: c input scanf


【解决方案1】:

我已更正您的代码以输入请求的值数量,希望对您有所帮助。

#include <stdio.h>
#include <stdlib.h>

#define SIZE_A (10)
#define SIZE_B (10)
#define SIZE_C (SIZE_A+SIZE_B)

int main()
{
    int A[SIZE_A] = {0}, B[SIZE_B] = {0};
    int A_input = 0, B_input = 0;
    int i;

    printf("First series length:\n");
    if (scanf("%d", &A_input) != 1)
        exit(1);
    if (A_input < 1 || A_input > SIZE_A)
        exit(1);
    printf("Enter %d numbers for first series:\n", A_input);
    for (i=0; i<A_input; i++)
        if (scanf("%d", &A[i]) != 1)
            exit(1);

    printf("Second series length:\n");
    if (scanf("%d", &B_input) != 1)
        exit(1);
    if (B_input < 1 || B_input > SIZE_B)
        exit(1);
    printf("Enter %d numbers for second series:\n", B_input);
    for (i=0; i<B_input; i++)
        if (scanf("%d", &B[i]) != 1)
            exit(1);

    return 0;
}

节目环节:

First series length:
3
Enter 3 numbers for first series:
1 2 3
Second series length:
4
Enter 4 numbers for second series:
7 8 9 10

【讨论】:

  • 我还没有解决您在评论中发布的关于合并两个数组的附加问题。请您自己尝试一下。
  • 感谢天气,但我没有使用循环来扫描输入是有原因的。每个系列的输入必须在一行中,例如:10 20 30 40... 当我使用循环时,它会不断地要求输入。我希望我的问题现在很清楚,OFC 请不要我自己做,只是这一步对我来说是个问题,以他们想要的方式获取输入
  • @lior 输入是否都在一行中并在每个行之间有一个空格,或者在不同的行上并在每个行之间有一个换行符并不重要 - 都是空格。在每个系列的最后一个条目之后,您只需要一个enter。请尝试一下。
  • @lior 我添加了示例输入会话。
  • 天啊,好的,现在我知道我的问题出在哪里了。我不应该在课堂上睡着。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多