c语言,为什么while(getchar()=='\n',这个语句不能用

#include<stdio.h>
void desplay(char cr, int line, int col);
int main()
{
char ch,m;
int line, col;
printf("请输入字符,列数,行数");
while ((ch = getchar()) != '\n')
{

scanf_s("%d %d", &line, &col);

desplay(ch,line, col);

printf("你可以再次输入");

while (getchar() == '\n')
continue;
}
printf("bye");
return 0;
}
void desplay(char cr, int line, int col)
{
int lines, cols;
for (lines = 1; lines <= line; lines++)
{
for (cols = 1; cols <= col; cols++)
putchar(cr);
printf("\n");
}

},必须写成while(getchar()!='\n',为什么是这样的,不然如果有换行符,就忽略呀,请解释一下

while (getchar()!='\n') ; 表示循环读入字符,直到读到回车符结束循环。

我们在输入一个数据时,一般都会按回车来确认输入结束,可是scanf()函数对最后的回车确认符并不丢弃,而是存储在缓存中,这样如果,下一个操作是读字符操作,则会将缓存中的回车符误读为实际数据,而造成程序运行异常。因此,在确认输入一个数据后,要回车来确认时,可通过while (getchar()!='\n') ;来清除缓存中的垃圾数据。
这个语句,还可以做到清除输入多余的字符,如:

1
2
3
4

char ch[11]; //最多能存储10个字符
getline( ch, 10 ); //输入10个字符,可是用户有可能输入10个以上的字符,于是可用上面的语句来清除缓存的数据。
while (getchar()!='\n') ;
这样,后续的读数据操作,就不会受这里的输入影响了。追问

while (getchar()=='\n'),为什么,不可以呀?缓存区有个\n,进入循环,contiune,忽略掉就可以了呀,请解释一下,我理解错在哪里

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答