Reputation: 25
I'm trying to enter input into an array via scanf()
. The 1st and 2nd scanf()
calls seem to work as I expect. The other two don't work, and I can't figure out why. Can anyone point out the problem?
Here's my code:
#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;
}
Upvotes: 0
Views: 119
Reputation: 34540
I have corrected your code to input the requested number of values, hope it helps you.
#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;
}
Program session:
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
Upvotes: 1