简体   繁体   English

在c中输入字符数组

[英]inputting array of characters in c

I have written this code to input two array of characters a and b of size 5 each.我已经编写了这段代码来输入两个大小为5的字符ab数组。

When I give the input :当我给出输入时:

abcde
abcde

the output b[2] should be c but it is giving as b .输出b[2]应该是c但它给出的是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 ?还记得在为第一个scanf输入abcde后按Enter 键吗? This character is consumed by the second scanf during the first iteration of the second for loop.该字符在第二个for循环的第一次迭代期间由第二个scanf消耗。

You can fix it by adding您可以通过添加来修复它

scanf("%*c");

or或者

getchar();

between the two for loops.在两个for循环之间。 This will scan and discard the newline character.这将扫描并丢弃换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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