首页 > 解决方案 > 显示星号与使用函数显示字符

问题描述

我编写了asterisksDisplay一个函数rowcolumn下面的程序完美运行。

#include <stdio.h>

void asterisksDisplay (int row, int column);

int main (void)
{
    int a=0;
    int b=0;
    printf("Please enter sides of your shape: ");
    scanf("%d%d", &a, &b);
    printf("\nYour shape is: \n");
    asterisksDisplay(a, b);
}

void asterisksDisplay (int row, int column)
{
    for (int i = 1; i <= row; i++) {
        for (int p = 1; p <= column; p++) {
            printf("*");
        }
        printf("\n");
    }
 }

当我尝试将此星号函数修改为用户给定字符显示的函数时,编译器会以某种方式跳过显示该字符。

#include <stdio.h>

void asterisksDisplay (int row, int column, char character);
int main (void)
{
    int a=0;
    int b=0;
    char c;
    printf("Please enter sides of your shape: ");
    scanf("%d%d", &a, &b);
    printf("\nplease enter the character to be filled: ");
    scanf("%s", &c);
    printf("\n");
    asterisksDisplay(a, b, c);
}

void asterisksDisplay (int row, int column, char character)
{
    for (int i = 1; i <= row; i++) {
        for (int p = 1; p <= column; p++) {
            printf("%c", character);
        }
        printf("\n");
    }
}

解决此问题的解决方案是什么?

标签: cscanf

解决方案


改变

 scanf("%s", &c);

 scanf(" %c", &c);
          ^^-----------------------(i)
       ^^------------------------- (ii)
  • 将转换说明符从%sto更改%c为 (i):因为c是一种char类型。

  • 我们需要转义先前输入的换行符,因此转换说明符之前的额外空格会匹配并丢弃缓冲区中存在的任何前导空格输入。


推荐阅读