设计一个函数chline(ch,i,j),打印指定的字符j行i列

这里涉及到scanf()函数的读取知识和缓冲区的知识

scanf函数在读取时候,是从缓冲区读取数据,而我们输入的数据会在保存在缓冲区,scanf函数从缓冲区读取的数据后,相应的数据会从缓冲区中消失,但是没有被读取的数据还会在缓冲区,在下次调用scanf函数时,scanf函数会先从缓冲区中读取这一部分数据。所以为了避免用户输入多余的数据影响后续程序的运行,需要运行clean函数 清除多余的数据。
clean函数的代码:
void clean(void)
{
	while (getchar() != '\n')	//获取缓冲区里的数据,只是读取不做其他操作,直到**\n**字符,获取后结束循环
		continue;
}
clean函数的运行示范:
  1. 不使用clean函数的情况:
#include<stdio.h>
void chline(char ch, int i, int j); //处理打印字符函数
void clean(void);
int main(void)
{
	char ch;
	int i, j;
	printf("Please enter the Number of columns and rows(q to quit): ");
	while (scanf_s("%d %d", &i, &j) == 2)	//获取两个数据,i列和j行,都为int类型
	{
		printf("Please enter you want to print character: ");
		scanf_s(" %c", &ch); //%c前面的空格可以跳过开头的空白字符输入
		chline(ch, i, j);
		printf("Please enter the Number of columns and rows(q to quit): ");
	}
	printf("Bye!\n");
	return 0;
}

void chline(char ch, int i, int j)
{
	for (int y = 1; y <= j; y++)
	{
		for (int x = 1; x <= i; x++)
			putchar(ch);
		putchar('\n');
	}
}

可能出现的错误结果:
第一种情况:
在这里插入图片描述
第二种情况:
在这里插入图片描述
总结:两种情况都是因为用户输入数据时输入错误,不规范导致的。

  1. 完整正确的代码:
#include<stdio.h>
void chline(char ch, int i, int j); //处理打印字符函数
void clean(void);
int main(void)
{
	char ch;
	int i, j;
	printf("Please enter the Number of columns and rows(q to quit): ");
	while (scanf_s("%d %d", &i, &j) == 2)	//获取两个数据,i列和j行,都为int类型
	{
		printf("Please enter you want to print character: ");
		clean();	///处理缓冲区剩余的字符,防止用户输入多余字符影响后面获取打印字符的操作
		scanf_s(" %c", &ch); //%c前面的空格可以跳过开头的空白字符输入
		chline(ch, i, j);
		printf("Please enter the Number of columns and rows(q to quit): ");
	}
	printf("Bye!\n");
	return 0;
}

void chline(char ch, int i, int j)
{
	for (int y = 1; y <= j; y++)
	{
		for (int x = 1; x <= i; x++)
			putchar(ch);
		putchar('\n');
	}
}

void clean(void)
{
	while (getchar() != '\n')
		continue;
}

总结:通过clean函数能有效的防止因为用户输入不规范导致的错误

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值