'Scanf in the third prompt get skipped, even if I add a space before the %d

My scanf function keeps getting skipped. Here is a sample for the code:

int size, size2;


  printf("Enter the number of elements in the first array: ");
  scanf("%d", &size);
  char arr[size];
  for (int i=0; i<size; i++){
    scanf("%c", &arr[i]);
  }
  printf("Enter the number of elements in the second array: ");
  scanf(" %d", &size2);
  char arr2[size2];
  for (int i=0; i<size2; i++){
    scanf("%c", &arr2[i]);
  }

The scanf for the size2 prompt is always skipped. Why is this?



Solution 1:[1]

You Can insert each step logs in your loops , ex :

printf("Enter the number of elements in the first array: ");
  scanf("%d", &size);
  
  char arr[size];
  
  for (int i=0; i<size; i+=1){
    printf("start of round %d  ",i);
    scanf("%c", &arr[i]);
    printf("end of round %d  ",i);
  }
  
  printf("Enter the number of elements in the second array: ");
  scanf(" %d", &size2);
  char arr2[size2];
  for (int i=0; i<size2; i++){
    printf("start of round %d  ",i);
    scanf("%c", &arr2[i]);
    printf("end of round %d  ",i);
  } 

content of logs in first loop:

start of round 0 end of round 0 start of round 1 (input !! # jump to round 1!)

...

you can use %s instead of %c

printf("Enter the number of elements in the first array: ");
  scanf("%d", &size);

  char arr[size];

  for (int i=0; i<size; i+=1){
    printf("start of round %d  ",i);
    scanf("%s", &arr[i]);
    printf("end of round %d  ",i);
  }

  printf("Enter the number of elements in the second array: ");
  scanf(" %d", &size2);
  char arr2[size2];
  for (int i=0; i<size2; i++){
    printf("start of round %d  ",i);
    scanf("%s", &arr2[i]);
    printf("end of round %d  ",i);
  }

This trick worked for me!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MohammadHossein