使用%d扫描字符 [英] Scanf a char using %d
问题描述
下面我有一个特定的示例,如果输入整数(请参见output1),该示例就可以很好地工作,当我尝试在scanf函数调用中使用%d说明符扫描char时,我得到下面的output2.
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.
所以,我的问题是,如果输入一个char,我希望类型说明符将其转换为等效的int值(如果不是垃圾值),即使在任何情况下都应打印/段错误.但是,在这里我得到了连续的打印,这是错误的,因为scanf每次都被绕过.我非常不确定背景中发生了什么,并且想知道相同的情况.
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\n", a);
}
return 0;
}
输出1 :
> 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 :用于输入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:我知道这是一个愚蠢的问题,询问在无效的情况下会发生什么情况,在这种情况下,非预期的类型说明符(在这种情况下为%d)用于不同的类型,但是我想知道在后台发生了什么,如果有的话.谢谢
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
推荐答案
您可以将scanf检查为 @chux )
You may check scanf as @Some programmer dude. You may compare the count arguments succesfully filled (Thanks to @chux)
在您的情况下,scanf找不到任何整数值,到达输入的末尾并返回EOF,而使a
变量保持不变.
In your case, scanf didn't find any integer value, reached the end of the input and returned EOF, keeping the a
variable untouched.
如果失败,它将返回EOF(请阅读 http://www.cplusplus. com/reference/cstdio/scanf/#return ).
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\n", a);
对于字符,最好使用getch()
或至少在scanf上要求"%c"
:
For characters, you better use getch()
or at least, ask for "%c"
on scanf:
if(scanf("%c", &a) == 1)
printf("entered key was %d\n", a);
您收到的垃圾"值就是程序存储器中的值,因为a
未初始化.
The "junk" value you recieve is what was in your program memory, because a
is not initialized.
这篇关于使用%d扫描字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!