C language scanf input buffer problem [Reserved]

Author: Abaka
Source: CSDN
Original: https://blog.csdn.net/qq_39032310/article/details/83692746

Many students may encounter when writing code on the scanf input buffer when reading problems.
First come Why is there this kind of analysis of the problem of scanf, scanf function is the standard input stream (receiving data from the keyboard), the received data into the input buffer, including the keyboard input box, enter these characters when you are receiving% d is not affected, but with% c will generate an error, this is because the "% c" input, spaces, and escape characters are as valid character will be received% c.
E.g:

#include<stdio.h>
int main()
{
	char a, b, c;
	scanf("%c%c%c", &a, &b, &c);
	printf("%c,%c,%c\n", a, b, c);
	system("pause");
	return 0;
}

The solution of these problems:

  1. Before receiving a second number of empty buffer, fflush (stdin); getch (); getchar (); can be a random, fflush (stdin) is all cleared, getchar () is a empty character, if there is the buffer extra characters will be used normally,
  2. Add space before the% c, spaces can absorb return character or space.

If you are in the cycle multiple input multiple characters scanf recommended, "" be separated, and should be used when the keyboard input ","

Published 73 original articles · won praise 90 · views 40000 +

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/85279400