【问题标题】:Taking character into array and printing it in C将字符放入数组并在 C 中打印
【发布时间】:2021-01-02 04:54:52
【问题描述】:

我对以下问题感兴趣: 将颜色作为字符(例如:'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 函数有问题。可能是什么问题?

【问题讨论】:

    标签: c for-loop char scanf conversion-specifier


    【解决方案1】:

    使用以下转换说明符

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

    这允许跳过例如对应于按下的 Enter 键的空格。

    也在这个循环之后

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

    放置语句

    putchar( '\n' );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 2012-01-03
      • 2014-12-21
      • 2015-12-13
      相关资源
      最近更新 更多