Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

c - Scanf a char using %d

I have a specific example below, which works perfectly fine if integers are inputted (see output1), when I try to scan a char using %d specifier in scanf function call I get the output2 below.

So, my question is if input a char I hope the type specifier should convert it to an equivalent int value, if not a junk value, even in the either case it should print/segfault. But, here I'm getting continuous prints which I feel is wrong as scanf is getting bypassed every single time. I'm pretty unsure what's happening in the background and would like to know the same.

#include <stdio.h>

int main()
{

   int a;

   while (1){
       printf("enter a number:");
       scanf("%d", &a);
       printf("entered number is %d
", a);
   }

return 0;
}

Output1:

>     enter a number:1
>     entered number is 1
>     enter a number:
>     3
>     entered number is 3
>     enter a number:4
>     entered number is 4
>     enter a number:5
>     entered number is 5 enter a number:

Output2: for input a

>     enter a number:entered number is 32767
>     enter a number:entered number is 32767
>     enter a number:entered number is 32767
>     enter a number:entered number is 32767
>     enter a number:entered number is 32767
>     enter a number:entered number is 32767
>     enter a number:entered number is 32767
>     enter a number:entered number is 32767
>     enter a number:entered number is 32767

PS: I know this is a stupid question of asking what happens in an invalid case where a type specifier unintended (%d in this case) is used for different type, but I would like to know what happens in the background, if any. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may check scanf as @Some programmer dude. You may compare the count arguments succesfully filled (Thanks to @chux)

In your case, scanf didn't find any integer value, reached the end of the input and returned EOF, keeping the a variable untouched.

On failure it'll return EOF (read http://www.cplusplus.com/reference/cstdio/scanf/#return).

if(scanf("%d", &a) == 1) //Check if exactly one parameter was read. 
    printf("entered number is %d
", a);

For characters, you better use getch() or at least, ask for "%c" on scanf:

if(scanf("%c", &a) == 1)
    printf("entered key was %d
", a);

The "junk" value you recieve is what was in your program memory, because a is not initialized.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...