gpt4 book ai didi

c++ - sscanf 在 MSVC++ 15+ 中有变化吗?

转载 作者:太空狗 更新时间:2023-10-29 20:51:13 25 4
gpt4 key购买 nike

给定以下代码段:

#include <iostream>
#include <cstring>
#include <cstdio>

int main()
{
char color[256];
float c,m,y,k;
const char* arguments = "0.8500 1 0 0 (Violet)";
memset(color, 0, 256 * sizeof(char));
if (sscanf(arguments, "%f %f %f %f %256c", &c, &m, &y, &k, color) == 5)
std::cout << color;
}

这已经投入生产并工作了至少 10 到 15 年(它输出颜色名称):

(Violet)

但是使用最新的 Microsoft Visual Studio 编译器,或者也在 MSVC++ 15 中,结果发生了变化。 结果是 4,而不是 5。使用 gcc 或 clang,结果也是 5,就像在以前版本的 MSVC++ 中一样。这段代码有什么问题吗?有人知道为什么编译器之间会出现这些不同的结果吗?

最佳答案

"%256c" 期望读取 正好 256 个字符,如 C 标准 (7.21.6.2 §12) 中所指定:

c Matches a sequence of characters of exactly the number specified by the field width (1 if no field width is present in the directive).

要获得您想要的行为,您可以使用例如。 "%255s",匹配最多 255 个(非空白)字符。

关于为什么这种行为在实现(的版本)之间不同的问题:似乎有几种实现没有强制执行 exactly 部分,而您使用的是。

由于您的代码依赖于非标准行为,因此在某些时候出现代码中断并不意外。

关于c++ - sscanf 在 MSVC++ 15+ 中有变化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51154152/

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