Knowledge point 14: About input

All inputs are stored in the buffer first, and when the carriage return is pressed (the line feed also enters the buffer), the data in the buffer is called once. When calling scanf and other functions, it is read from the buffer. Wait for the user to input again until the data in the buffer is read.

1. About scanf

1. When entering a single character

When there is a space before %c, scanf(" %c", &a);scanf starts to read from the first non-blank character in the buffer, that is, no matter how many spaces are entered, carriage returns, or tabulation are useless.
When scanf("%c", &b);there is no space before %c, all the keyboard input can be read by scanf (including line feed, space, tabulation), and the
last entered carriage return also exists in the buffer.

2. When entering numbers

Spaces, carriage returns, and tabulation will end one input.
Double type floating-point numbers can only be input by %lf (%lf can only be used to input double-type floating-point numbers), and both %f and %lf can be used for output.

3. When entering a character string

Scanf cannot read newline characters when reading a string.

	char str1[20], str2[20], c;
	scanf("%s", str1);
	c = getchar();//输入str1时最后的换行符仍保留在缓冲区,可以作为单个字符被直接读入 
	//但若之后接着为用scanf输入另一个字符串,则输入str1时最后的换行符不能进入字符串str2,因此str2[0]不为换行符。
	//输入的换行符会积累在缓冲区中

Therefore, after using scanf, or by digested with getchar while (getchar ()! = ' \ N') ( universal), or added in a scanf \ n i.e., scanf("%d\n", &n);may also be used after scanf fflush(stdin);to empty the buffer.

2. About gets

When inputting a string with gets, the carriage return number is converted to'\0' to indicate the end of the string input, so the carriage return will not remain in the buffer.
When inputting with gets, only carriage return can end the input.

3. About puts

The puts function converts the terminator'\0' into a newline character'\n', so it will automatically wrap after calling puts

4. About getchar

When using getchar to input characters, the carriage return will be used as a character!

Guess you like

Origin blog.csdn.net/Shao_yihao/article/details/113444361