scanf并保持char作为整数 [英] scanf and keeping char as an integer

查看:213
本文介绍了scanf并保持char作为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是不能得到它。
Char是一个整数,对不对?所以我可以做

I just can't get it. Char is an integer, right? So I can do

int var;
scanf("%d", &var);
I:[65]
printf("%c", var);
o:[A].

为什么wrog要做:

char var;
scanf("%d", &var);
I:[A]
printf("%d", var)
O:[-1236778]


推荐答案

在第二个 scanf()

scanf("%d", &var);

scanf()解析打印指令%d 。这意味着参数& var 预期是 int 的地址。而是给出了 char 的地址。 int 的大小肯定大于 char 的大小。因为 scanf()试图将一个 int 大小的金额放入一个只为一个'char'可能发生scanf()可能放置数据是它不应该是的地方。尝试将10磅pf土豆放在5磅袋中。

the scanf() parsed the print directive %d. This implies that the argument &var is expected to be the address to an int. Instead the address to a char was given. The size of an int is certainly larger than the size of a char. As scanf() attempts to place an int size amount into a place meant only for a 'char', strange things can happen for scanf() may place data is places it should not. Trying to put 10 pounds pf potatoes in a 5 pound sack.

此外,它似乎怀疑 scanf(%d,& var ); 成功读取输入A。 scanf()会看到 A ,因为它不是一个数字,会放弃扫描文本输入满足 int 定义。因此,您的 scanf(%d,& var)可能返回值 0 var 中的任何。保存你的培根,如果它,它会把数据放在空间不应该。

Further - it appears doubtful that scanf("%d", &var); successfully read the input "A". scanf() would see the A, and since it is not a digit, would give up scanning for textual input that meets an int definition. Thus your scanf("%d", &var) likely returned a value of 0 and thus did not place anything in var. Saving your bacon, for if it did, it would place data in space it should not.

最后 printf(%d,var )然后只是打印出从未设置的 var ,所以你得到发生在char 。 -1236778 似乎不太可能。我怀疑帖子不匹配代码也不输入/输出在一些小的步调。

The final printf("%d", var) is then simply printing out the var which has never been set, so you get whatever happened to be in char. -1236778 seems unlikely. I suspect that the post does not match the code nor the input/output in some small pace.

这篇关于scanf并保持char作为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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