简体   繁体   中英

What exactly happens when I input a string “abcd” to scanf(“%d”, &var)?

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM