第3和第4次扫描没有输入

时间:2015-12-03 19:37:19

标签: c input scanf

我试图通过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;
}

1 个答案:

答案 0 :(得分: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