foreword
Today, I was attracted by a group friend's question in the group. He wanted to convert lowercase letters to uppercase letters, and then he could loop infinitely like this
This is the code he wrote. I asked everyone why the program does not loop. He entered a, and it would output A, but the program exited directly and would not let you enter the next data. I looked at the code and put aside the writing method , I looked at the grammar, no problem, there should be a loop, why is there no loop? But he insisted that there was no loop, and he even posted a video. I was a little confused. There is nothing wrong with the grammar. How could it not loop, so I tried it myself, and the result is as follows
#include<stdio.h>
int main()
{
char n;
int i;
scanf("%c",&n);
if(n>='a'&&n<='z')
{
do
{
i=n;
printf("%c",i-32);
scanf("%c",&n);
}while(n>='a'&&n<='z');
}
return 0;
}
Oh My God? There is really no loop for us to enter data, and the program exits directly? what's up?
Then I thought about it, the grammar is indeed no problem, and it can run. Since the program exits directly, it should be that the conditions in the while are not met, so I directly locked my eyes on the scanf() statement. Speaking of this , I naturally thought of the buffer zone, I checked the information later and some of my own understanding before, and found the answer
reason
scanf() When "%c" receives a character type, whether it is a number or a space, a carriage return, or a tab key will be received as a character
Then scanf () has another problem: if you input a, then there are a and \n in the scanf buffer, and then only a will be read when the stdin stream is read, and assigned to the corresponding variable, \n is also Stay in the buffer, as mentioned earlier, the newline will be read as a character, so when entering the loop, this scanf() directly reads the \n of the buffer and assigns it to n, then n enters the while condition judgment, and naturally it will not be established, so the program exits directly
Solution
Clear the buffer after each scanf(), you can use the following two functions
①fflush(stdin);
②getchar();
the case
After listening to the above explanation, make a small question and ask: In the following program, how many times do we have the opportunity to input data?
If I input csdn, what is the output
int main()
{
char n,n1;
scanf("%c",&n);
scanf("%c",&n1);
printf("%c",n1);
return 0;
}
The answer is 1 chance of input, and the output is s, because no matter what you input for the first time, if you don’t update the buffer, the next scanf() will automatically read, it may be a newline, a space or the rest of the input content Content that matches the character
I was studying at first, but after seeing the group of friends posting questions, I studied it for half an hour. It was also very interesting and rewarding.
If this article is beneficial to everyone, please give it a thumbs up~