0

Inputting a string to

scanf("%d",&var) returns 0.

There is a similar question here, but the explanation of what happens internally is not provided. What is provided is a way to handle the situation.

How exactly does GCC handle strings passed to scanf("%d",&var) and why is the return value 0 in this case?

Community
  • 1
  • 1
xennygrimmato
  • 2,646
  • 7
  • 25
  • 47
  • 2
    That's actually your standard C library, not Gcc, what's doing something here (ignoring built-in functions). And Gcc never sees the string passed in at runtime. – mafso Jun 30 '14 at 14:32
  • 1
    And I don't fully understand your question (or at least not, what isn't answered in the linked question). Is it, how a byte can be read from a stream and then pushed back in case it is an invalid byte? And for implementation details: Take a look at e.g. the `glibc` source code. – mafso Jun 30 '14 at 14:37
  • > _"Is it, how a byte can be read from a stream and then pushed back in case it is an invalid byte?"_ That is exactly what I want to understand. – xennygrimmato Jun 30 '14 at 14:41
  • 1
    [Here](https://sourceware.org/git/?p=glibc.git;a=blob;f=stdio-common/vfscanf.c) is the aforementioned source code, they use the built-in function `_IO_sputbackc` defined in [genops.c](https://sourceware.org/git/?p=glibc.git;a=blob;f=libio/genops.c). You may also want to take a look at the standard C functions `ungetc` and `fseek`. An answer to your question will depend on the platform in use, but at least you have a few points where to start now… – mafso Jun 30 '14 at 15:48

2 Answers2

3

Upon successful completion, scanf shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure.

On seeing %d in format string, scanf expects an int type data. When you enter string in place of int, scanf starts reading input and when sees character, stop reading and returns 0 .

haccks
  • 104,019
  • 25
  • 176
  • 264
3

On success, the function returns the number of items of the argument list successfully filled. So, if you don't type a number, the number of items read will be 0.

Refer to http://www.cplusplus.com/reference/cstdio/scanf/ for more info

BlueMoon93
  • 2,910
  • 22
  • 39