gpt4 book ai didi

c - 如何使用 scanf unsigned int

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:06 25 4
gpt4 key购买 nike

我有以下内容

 unsigned int value = 12;
int res = std::sscanf("-567", "%u", &value);

运行时 res 为 1,表示 1 个匹配项,值设置为 4294966729而我原以为不会匹配

如果有人能解释这种行为,我将不胜感激。

最佳答案

C11 Standard states

“...其格式与 strtoul 函数的主题序列的预期格式相同,基本参数的值为 10 ...”

并且,for strtoul

“...如果主题序列以减号开头,则转换产生的值取反...”

#include <stdio.h>

int main(void) {
unsigned int value;
int res;

res = sscanf("-567", "%u", &value);
if (res == 1) {
printf("Value: %u\n", value);
} else {
fprintf(stderr, "Error\n");
}

res = sscanf("567", "%u", &value);
if (res == 1) {
value = ~value + 1; // add 1 in two's complement machines
printf("Value: %u\n", value);
} else {
fprintf(stderr, "Error\n");
}

return 0;
}

关于c - 如何使用 scanf unsigned int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38872327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com