gpt4 book ai didi

c - 当我使用多个字符串时函数 sscanf_s 失败

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

我不明白为什么下面的代码会失败:

char    toto[54], titi[54]; //I already tried with allocations

sscanf_s(line, "%s-%s", &toto, &titi, sizeof(toto) + sizeof(titi));

sscanf_s(line, "%s-%s", &toto, &titi, sizeof(toto) + sizeof(titi));

我的问题只是字符串(float、int、double 等。没问题),我使用的是 Visual 2010。

有人有想法吗?非常感谢您的回答。

最佳答案

来自sscanf_s()引用页:

The sscanf_s function reads data from buffer into the location given by each argument. The arguments after the format string specify pointers to variables with a type that corresponds to a type specifier in format. Unlike the less secure version sscanf, a buffer size parameter is required when using the type field characters c, C, s, S and [. The buffer size in characters must be supplied as an additional parameter after each buffer which requires it. For more information, see scanf_s, _scanf_s_l, wscanf_s, _wscanf_s_l and scanf Type Field Characters.

意思是每个缓冲区后面必须跟着它的大小:

sscanf_s(line, "%s-%s", toto, sizeof(toto), titi, sizeof(titi));

此外,- 不是空白字符,不会作为 "%s" 格式说明符的终止符,因此如果 line 包含 hello-world 然后它会被读入 tototiti 不会被赋值。要将 - 用作终止符,请使用扫描集:

if (2 == sscanf_s(line, "%[^-]-%s", toto, sizeof(toto), titi, sizeof(titi)))
{
/* Both 'toto' and 'titi' where assigned. */
}

关于c - 当我使用多个字符串时函数 sscanf_s 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13279209/

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