Bloggers have recently been learning C programming, and the following code snippet appears in the code example in the book:
#include <stdio.h>int main () {char a[5];int i;printf ("Enter value: \ n"), for (i=0;i<5;i++) { scanf ("%c", &a[ I]); //Why add a GetChar ()?} printf ("\ n"); for (i=0;i<5;i++) { printf ("%c", A[i]);} GetChar (); return 0;}
Run results
For beginners bloggers do not understand, why scanf get input characters, but also add a getchar () it?
Then the statement is removed, and the program runs input to the C character and the jump ends.
Miss no sister, so ask for beautiful degrees Niang ....
Mouse strokes ...
Ding Ding. Finally found that other friends also have the same confusion:
One enthusiastic Netizen answered very in place (HTTPS://ZHIDAO.BAIDU.COM/QUESTION/147733301.HTML?FR=IKS&WORD=C+GETCHAR+SCANF&IE=GBK):
C language in the reading of keyboard data, usually with a cached data input, you need to press ENTER to complete the "line" data input confirmation.
The scanf () function does not handle the return confirmation, and the carriage return is left in the input buffer.
Therefore, the next read of the "character" action function (GetChar, scanf ("%c"), get (), and so on) will read this character when it is run.
When reading numeric data or strings, scanf () starts reading from the first non-whitespace character (blank character: Carriage return, space, tab), automatically ignores the preceding whitespace character, and encounters a white-space character to end the input of that type of data.
Therefore, whether it is necessary to eat back with a getchar after scanf, to see what the next input data type is, if it is read character class operation, there are many ways to deal with it:
First, forcibly flush the input cache with fflush (stdin) command, discard the data in the input cache, this method is valid under Windows, Linux is invalid.
| 1 2 3 |
charch;fflush(stdin); //不管缓存中有没有数据,强行清除ch=getchar(); //这里会等待用户输入一个字符 |
Second, the front has read data operation, now to perform the read character operation, you can use GetChar () to eat the front of the return confirmation
| < Em>1 2 3 4 5 |
int i; char CH; scanf ( , &i ) //read an integer, enter confirm getchar (); //first eat the return confirmation, these two sentences, the effect of the next method of the sentence ch= getchar // This will wait for the user to enter a character |
Third, in the scanf () writing, such as: read a data, to enter the confirmation, the output is written in the following format
| 1 2 3 4 |
int i;char ch;scanf("%d%*c", &i ); //%*c表示读一个字符,并不赋值给任何变量ch=getchar(); //这里不会读到回车符 |
The problem is finally enlightened, the original plus GetChar () is to put the input character data after the strike of the carriage return from the cache, so that the next input process will not be affected.
C language Programming--scanf () function with GetChar () function to understand input cache (buffer) of C program