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]);
}
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments