简体   繁体   中英

inputting array of characters in c

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM