Scanf (% d, ..) in a loop when the given char does not block once

I wrote this code:

char str[10]; while(1) { scanf("%d",str); } 

if a char is given (for example, 'a'), the loop just continues without stopping and asking for more input (scanf does not block suddenly)

why?:-)

+4
source share
6 answers

Because a not a decimal integer. scanf will try to read it, but not execute or advance its internal pointer, so it will endlessly try to read the same a as a decimal and fail.

consider the following program:

 int d; char c; scanf("%d", &d); scanf("%c", &c); 

if you enter a , the first scanf will fail, and the second will read ' a ' in c . This should explain the problem :)

+3
source

Since it cannot force 'a' into integer form, therefore it "returns it to the stream" (there is no real stream there, just a manner of speaking). Then your endless loop makes him try the same procedure again. Infinitely.

+1
source

Your format string is %d not %s . Scanf() searches for an integer, not a string. Your loop holds forever because it says while(1) , so it never ends.

0
source

He may be trying to read int , but then he notices that there is no int in the data stream, so he returns immediately. If it does not consume the input stream, it will do it again.

0
source

input buffer has a....

your scanf trying to read int:

  a ....
      ^
      oops: cannot be int.  stop scanfing

and in the next loop, a still exists.

scanf is generally difficult to use correctly, but you should always check its return value:

 int chk; chk = scanf(...); /* pseudo-code */ if (chk != EXPECTED_VALUE) { /* HANDLE ERROR! */ } 
0
source

To fix this, you need to check that scanf () actually reads the values ​​you need. scanf () returns the number of successfully read items. So, save the return value, check if it is 1. If it is 0, then 0 elements have been read, and you need to clear the stream before trying again. (edit: Well, maybe it’s not necessary to empty it, but at least go past the offensive data in the stream)

As others said, he tries to read an integer, sees 'a' , cannot read an integer, but then 'a' is still in the stream when he tries again.

0
source

All Articles