C程序跳过用户输入?

3
我正在制作一个程序,该程序从用户处获取包含多少个数字的数组以及这些数组中包含哪些数字的输入,然后比较两者以查找它们的联合和交集。
我已经编写了代码,但是有一个问题。当用户输入第一个数组(a)中需要多少个数字以及这些数字是什么时,它会跳过整个第二个数组(b)的用户输入。
联合和交集的计算是正确的(未显示),但我无法弄清楚我缺少了什么。由于我对C语言还很陌生,可能有些小问题我没有注意到。
感谢您的帮助!
int main(void){

    int i, j, x, y;
    int elemA, elemB;
    int a[10] = {0};
    int b[10] = {0};


    // Prompts user to enter the amount of numbers that will be in array a
    // then asks user to enter the values (0-9) to be inputted.
    printf("Enter the number of elements in set A: \n");
       scanf("%d", &elemA);
    printf("Enter %d number(s) for set A: \n", elemA);
       scanf("%d", &x);
       if(x < 10)
          a[x]=1; // sets the index in the array to 1 if the
                  //corresponding number that has been inputted


    // Prompts user to enter the amount of numbers that will be in array a
    // then asks user to enter the values (0-9) to be inputted.
    printf("Enter the number of elements in set B: \n");
    scanf("%d", &elemB);
    printf("Enter %d number(s) for set B: \n", elemB);
       scanf("%d", &y);
       if(y < 10)
          b[y]=1; // sets the index in the array to 1 if the
                  //corresponding number that has been inputted

*** rest of code ***

1
scanf("%d", &x); 只能读取一个数字。你需要在某个地方加入循环。 - kaylum
1个回答

2

在这里:

printf("Enter %d number(s) for set A: \n", elemA);
scanf("%d", &x);

您只读取了一个整数,其他整数已排队,当您下次使用scanf时将使用它们,而不需要用户输入。


那很有道理。我的代码开始使用for循环返回一些奇怪的数字,但我会解决的。非常感谢! - Ashley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接