Sometimes scanf ("% C", & Ch) should have blocked waiting for the user to enter a char type data, but why should it be skipped? For example, in this section, int year;
Printf ("enter a year: \ n ");
Scanf ("% d", & year );
// Setbuf (stdin, null); // or use getchar () directly ();
// Enter one character on the keyboard to display its type (numbers, uppercase letters, lowercase letters, and others)
Char ch;
Printf ("enter a character: \ n ");
Scanf ("% C", & Ch );
If (CH> = '1' & Ch <= '9 ')
Printf ("this is digital \ n ");
Else if (CH> = 'A' & Ch <= 'B ')
Printf ("This is capital letter \ n ");
Else if (CH> = 'A' & Ch <= 'Z ')
Printf ("This Is letter \ n ");
Else
Printf ("other! \ N "); outputs:
Enter a year:
2000
Enter a character
:
Other!
Example 2:
The following sections:While (n <= 0)
{
Printf ("Enter the string length: \ n ");
Scanf ("% d", & N );
}
Setbuf (stdin, null); // <1>
Char A [n], B [N];
Printf ("input string: \ n ");
For (INT I = 0; I <n; I ++)
{
Scanf ("% C", & A [I]);
}
Printf ("output string: \ n ");
For (INT I = 0; I <n; I ++)
{
B [I] = A [n-1-i];
Printf ("% C", B [I]);
} If the <1> statement is removed, an error is returned. Example:
Enter the string length:
5
Input string
:
Hello
The output string is:
Lleh
To solve the root cause, let's take a look at how scanf () accepts data.
First, when our PC points to scanf, the system does not wait for user input, but determines whether the input buffer contains formatted content. If so, it will read it directly.
After knowing this, I should understand that scanf ("% C", & Ch); does not read data, but data we don't know.
The problem arises again. What does it read ??
Well, we need to talk about row caching;
When we use scanf (), we need to press the Enter key. Where did we go after the Enter key is pressed ??
Okay, you should have known the problem. The enter key also enters the input cache, that is, scanf ("% C", & Ch );
Read '\ n ';
The solution is very simple. Since there is something in the cache area, we can clear it ~~
Setbuf (stdin, null); (both in Windows and Linux)
Fflush (stdin); (Windows only );
Scanf ("% C", & Ch) directly skipped