Cly*_* B. 37 c windows mingw scanf c99
我在尝试 inttypes.h 时编写的简单程序:
#include <stdio.h>
#include <stdbool.h>
#include <inttypes.h>
bool get_bit(uint32_t x, uint8_t n) {
x >>= n;
return x & 1;
}
int main() {
uint32_t x;
uint8_t n;
printf ("Enter x: ");
scanf("%"SCNu32, &x);
printf ("Enter n: ");
scanf("%"SCNu8, &n);
printf("The %"PRIu8"th bit of %"PRIu32" is: %d", n, x, get_bit(x, n));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我的手机(64 位八核 ARN LTE Soc Android 10)上,它工作正常:
Enter x: 1
Enter n: 0
The 0th bit of 1 is: 1
Run Code Online (Sandbox Code Playgroud)
但在我的计算机(64 位 x86 Windows 10)上我得到:
Enter x: 1
Enter n: 0
The 0th bit of 0 is: 0
Run Code Online (Sandbox Code Playgroud)
将 bool 更改为 uint8_t 不会影响它。
编辑:我尝试使用 MinGW-w64 GCC C99 和 C17 进行编译。
Lun*_*din 40
如果您使用的 Windows 编译器使用 Microsoft 不兼容的 CRT(非)标准库,您可能会遇到此问题。即:Visual Studio 或 Mingw64/gcc。
我可以在 Mingw/gcc 上重现它。Microsoft CRT 损坏是一个众所周知的问题,例如不支持 C99 中引入的各种格式说明符。问题似乎在于scanf使用错误的格式说明符进行读取,因为在启用所有警告的情况下进行编译时,我得到:
警告:格式 [-Wformat=] 中存在未知转换类型字符“h”
%hh是位于引擎盖下的内容,SCNu8但编译器只读取到%h并停止在那里。实际调用scanf失败。
您至少可以使用以下命令在 Mingw 中解开 CRT 库:
#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
Run Code Online (Sandbox Code Playgroud)
当我将上述内容添加到您的代码中时,我得到了The 0th bit of 1 is: 1.
没有上面的补丁我得到The 0th bit of 0 is: 0
| 归档时间: |
|
| 查看次数: |
2412 次 |
| 最近记录: |