2

I have written this code to input two array of characters a and b of size 5 each.

When I give the input :

abcde
abcde

the output b[2] should be c but it is giving as b.

#include <stdio.h>

using namespace std;

int main(){

   char a[5], b[5];
   int i;
   for(i = 0; i < 5; i++){
       scanf("%c", a + i);
   }

   for(i = 0; i < 5; i++){
       scanf("%c", b + i);
   }

    printf("%c", b[2]);
}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Ishan Bansal
  • 99
  • 1
  • 8

1 Answers1

2

Remember pressing Enter after typing abcde for the first scanf? This character is consumed by the second scanf during the first iteration of the second for loop.

You can fix it by adding

scanf("%*c");

or

getchar();

between the two for loops. This will scan and discard the newline character.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83