关于C/CPP字符输入,scanf(“%c”,&a)可能存在的问题(Possible problems with scanf (‘% C’, & A) about C / CPP character input)

发现问题

刷题时,一个字符矩阵输入,scanf(“%c”,&g[i][j]),发现g[0][0]是空白。原来是忘了C的基础知识,getchar()和scanf(“%c”,&a)都会吸收空白字符

相关知识

scanf输入(除开占位符是%c的情况):

abc[回车]后,遇到回车结束,但是回车还留在输入流中。下一个scanf在输入前碰到回车,会自动把回车抛弃,然后再输入:efg,再碰到回车结束。所以加了getchar()时,它会吃掉一个回车。如果不加,在输入前,它会自动删除这个回车,所以结果是一样的。
重点:空格、回车、跳格等结束符在输入前碰到的话,会自动抛弃,输入后碰到的话,就会认为结束。

占位符是%c的情况

scanf遇到回车、空格等空白字符会吸收,完成输入,所以一般这种情况完成输入之后加上一个getchar()吸收掉多余的回车

————————

discover problems

When brushing questions, input a character matrix, scanf (“% C”, & amp; G [i] [J]), and find that G [0] [0] is blank. I forgot the basic knowledge of C. both getchar () and scanf (‘% C’, & amp; a) absorb white space characters

Relevant knowledge

Scanf input (except when the placeholder is% C):

After ABC [Enter], the end of enter is encountered, but the enter remains in the input stream. When the next scanf encounters a carriage return before entering, it will automatically discard the carriage return, and then enter: EFG, and then encounter the carriage return end. So when getchar () is added, it will eat a carriage return. If not, it will automatically delete the carriage return before entering, so the result is the same.
Key points: if the space, carriage return, skip and other terminators are encountered before input, they will be discarded automatically. If they are encountered after input, they will be considered to be over.

Placeholder is% C

Scanf will absorb carriage returns, spaces and other blank characters and complete the input. Therefore, in this case, a getchar () is added after the input to absorb the redundant carriage returns