The following code:
#include<iostream>using namespace std;int main(){ int m; while(1==scanf("%d",&m)) { puts("OK"); } system("pause");}
This code can be a correct loop, that is, the input integer outputs OK, and then waits for the next input to continue. Note: scanf ("% d", & M) returns the number of successfully read variables if early match is successful. Here there is only one variable M, so 1 is always returned.
But the code is as follows:
while(scanf("%d",&m)!=1)
Just replace =! =, As I imagine, if the input is not an integer, the output is OK, and then wait for the next input. The actual situation is that the output is always OK and will never stop.
Cause:
Scanf () is the read buffer. If you do not enter a number, the read will fail and the buffer will not be empty. So it keeps reading.
Method 1:
Use fflush to solve the problem.
The changes are as follows:
while(scanf("%d",&m)!=1){ puts("OK"); fflush(stdin);}
Method 2:
It seems that GCC does not support fflush. I tried using GCC in Linux and still cannot exit the loop, but no error is reported.
while(scanf("%d",&m)!=1){ puts("OK"); getchar();}
The original getchar () parameter is used to clear the input stream buffer, but there is also a problem.
If I input multiple non-integers in a row, this loop will output multiple OK statements. For example, if I enter ABCDE, the buffer zone contains these five characters. If getchar () is cleared at a time, the loop will be 5 times. Is there any way to clear the buffer at a time no matter how many characters are entered?
Method 3:
while(scanf("%d",&m)!=1){ puts("OK"); char c; while((c=getchar())!= '\n' && c != EOF );}
Perfect solution.
Method 4. 1: setbuf (stdin, null)
while(scanf("%d",&m)!=1) { puts("OK"); setbuf(stdin,NULL); }
This is also a good method, but there is also a problem. The first time you input ABCDE, you can close the buffer and output OK. However, if you input ABCDE In the second loop, five consecutive OK will appear.
Method 4.2:setbuf
(stdin,inbuf)
int main(void){ int m; char inbuf[50]; while(scanf("%d",&m)!=1) { puts("OK"); setbuf(stdin,inbuf); } return 0;}
It can also be solved.