c - 显示星号与使用函数显示字符
问题描述
我编写了asterisksDisplay
一个函数row
(column
下面的程序完美运行。
#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");
}
}
解决此问题的解决方案是什么?
解决方案
改变
scanf("%s", &c);
至
scanf(" %c", &c);
^^-----------------------(i)
^^------------------------- (ii)
将转换说明符从
%s
to更改%c
为 (i):因为c
是一种char
类型。我们需要转义先前输入的换行符,因此转换说明符之前的额外空格会匹配并丢弃缓冲区中存在的任何前导空格输入。
推荐阅读
- java - 使用 aspose 单元格从另一个 excel 中提取的 excel 文件未打开
- reactjs - API 支持的 React SPA 的 app_offline 和 index.html
- sql - Oracle SQL 中的 FROM 子句中的子查询失败
- android - 如何在 GridView 中显示 Firebase 存储图像
- ajax - 如何更改 Ajax 分页(页面列表)以加载更多?
- c# - C# - 从基类型中选择多态方法
- node.js - 在@azure/ms-rest-nodeauth 的设备代码流中指定范围
- csv - 在两个微服务之间发送文件
- json - 如何在应用程序屏幕上从 JSON 自动更新?SwiftUI
- python - 使用 dcc.Store 在另一个页面中绘制 Dash 共享回调输入