如果 C 尝试扫描整数变量中的字符会发生什么 [英] What happens if C tries to scan character in integer variable

查看:15
本文介绍了如果 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 内存中的一个位置吗?

is this 1986895412 a place in the ram ??

推荐答案

在这种情况下,scanf 指令会失败.引用 this answer(实质上改写了规范的定义):

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.

因此,number 保持与指令之前相同的值.由于您没有使用某些定义的值(例如 int number = 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天全站免登陆