C 中带有 CodeBlocks IDE 的 Scanf 函数有问题吗?

Scanf function in C with CodeBlocks IDE is buggy?

我 运行 我的 CodeBlocks 中有一些简单的代码,我想知道为什么 scanf 函数不能正确处理短裤!

下面的代码就是一个例子。该代码从用户那里获取三个 int 数字,然后再次打印它们,就这么简单 — 但打印的值与输入的值不匹配。

#include <stdio.h>

int main()
{
    short x, y, z;
    printf("Please enter three integers! ");
    scanf("%d %d %d", &x, &y, &z);
    printf("\n num1  =  %d  , num2 = %d  , num3  = %d ", x, y, z);

    return 0;
}

短 != 整数

您将指针传递给(通常为 2 个字节)数据,而 scanf 期望并写入 4 个字节

short x , y , z ; 更改为 int x , y , z ;

一如既往,scanf 没有错误,但编码器是:)

PS忘记补充了。您还可以使用 h 格式修饰符。如果你想扫描 char 大小的变量,还有 hh

说明符 %d 仅用于 int 变量,但在 short 的情况下,您必须使用 %hi 说明符而不是 %d

所以您的代码必须是:

#include <stdio.h>

int main() {
   short x , y , z ;
   printf("Please Enter three int Numbers ! ");
   scanf("%hi %hi %hi",&x,&y,&z);
   printf("\n num1  =  %hi  , num2 = %hi  , num3  = %hi ",x,y,z);
   return 0;
}

您可以在此处找到有关 C 数据类型及其说明符的更多信息: https://en.wikipedia.org/wiki/C_data_types