将字符放入数组并用C打印

问题描述

我对以下问题感兴趣: 将颜色作为字符(例如:“ y”表示黄色,“ r”表示红色等)并排列成阵列。显示时,每个字符之间应有一个空格。为此,我编写了以下代码

#include <stdio.h>


 int main(){

char a[10];
int i,n;
printf("Enter the number of colors (less than 10)\n");
scanf("%d",&n);
printf("Enter colors as alphabets : ");
for (i = 0; i < n; i++){
    scanf("%c",&a[i]);
}
printf("Entered colors are : ");
for (i = 0; i<n; i++){
    printf("%c ",a[i]);
}

return 0;
 }

如果我将数组的大小输入3,将颜色输入为r y g,则输出不会打印所有三个输入,而只会打印一个。 我几乎没有意识到scanf函数有问题。可能是什么问题?

解决方法

使用以下转化说明符

scanf(" %c",&a[i]);
      ^^^

这允许跳过例如与按下的Enter键相对应的空白。

也在此循环之后

for (i = 0; i<n; i++){
    printf("%c ",a[i]);
}

放置语句

putchar( '\n' );