这里涉及到scanf()函数的读取知识和缓冲区的知识
scanf函数在读取时候,是从缓冲区读取数据,而我们输入的数据会在保存在缓冲区,scanf函数从缓冲区读取的数据后,相应的数据会从缓冲区中消失,但是没有被读取的数据还会在缓冲区,在下次调用scanf函数时,scanf函数会先从缓冲区中读取这一部分数据。所以为了避免用户输入多余的数据影响后续程序的运行,需要运行clean函数 清除多余的数据。
clean函数的代码:
void clean(void)
{
while (getchar() != '\n') //获取缓冲区里的数据,只是读取不做其他操作,直到**\n**字符,获取后结束循环
continue;
}
clean函数的运行示范:
- 不使用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');
}
}
可能出现的错误结果:
第一种情况:
第二种情况:
总结:两种情况都是因为用户输入数据时输入错误,不规范导致的。
- 完整正确的代码:
#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函数能有效的防止因为用户输入不规范导致的错误