Notes on scanf() function in C language

Notes on scanf() function in C languageinsert image description here

Program flow: Input the number i of a character array, print out the value of i and then use dynamic memory allocation, malloc(i+1) allocates one more byte space for the terminator '\0', after the memory allocation is successful, give the character The array ch[ ] is assigned one by one. Note: When using the scanf() function to input, press the Enter key to end the input. The Enter key will affect the normal input and output of the following program (ch[0] outputs Enter). When there is a scanf statement before accepting the character ch, the carriage return of scanf is in the buffer, and at this time, getchar() should be used to eat the carriage return .

Example: Input 3, assign character array a, b, c
to output the array: ch = abc

1. The output result without using getchar() and not eating the carriage return is as shown in the figure below:
insert image description here
2. Using getchar() and the output result of eating the carriage return is as follows:
insert image description here

Guess you like

Origin blog.csdn.net/William_swl/article/details/120393857