如果C试图在整型变量扫描的性格会发生什么 [英] What happens if C tries to scan character in integer variable

查看:104
本文介绍了如果C试图在整型变量扫描的性格会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在想,如果用户在整型变量输入字符时会发生什么,例如:

So I was wondering what happens if the user enters characters in integer variables for example:

main()

    {

    int number;

    printf("Print a number:");
    scanf(" %d", &number);
    printf("The result is:%d", number);

    return 0;

我输入的字符,其结果是:1986895412

I typed in characters and the result is: 1986895412

这是1986895412在RAM中的位置?

is this 1986895412 a place in the ram ??

推荐答案

在这种情况下, scanf函数指令只是会失败。引用这个答案(基本上rephrases规范的定义):

In this case, scanf directive just fails. Quoting this answer (which essentially rephrases the spec's definition):

在%D转换符预期输入文本格式化为
  十进制整数。如果不是,则转换失败和字符
  导致失败的转换在输入流中左

The %d conversion specifier expects the input text to be formatted as a decimal integer. If it isn't, the conversion fails and the character that caused the conversion to fail is left in the input stream.

因此​​,数量仍然与它的指令之前有同样的价值。由于你没有一些规定值初始化(如 INT数= 0 ),这将是只是一些随机的垃圾值。你的情况也发生在等于 1986895412

So, number remains with the same value it had before the directive. As you didn't initialize it with some defined value (like int number = 0), it'll be just some random garbage value. In your case that happened to be equal to 1986895412.

这篇关于如果C试图在整型变量扫描的性格会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆