gpt4 book ai didi

c - 使用 scanf 读取无分隔符

转载 作者:行者123 更新时间:2023-11-30 15:21:48 25 4
gpt4 key购买 nike

用户输入的示例:

A10

尝试读取此输入

scanf_s("%c%d", &playerX, &playerY, 10);

用户的输入是否需要分隔?可以这样读吗?

编辑:我已经对此进行了测试,它只是崩溃了。

编辑2:解决方案:scanf_s("%c%d", &playerX, 1, &playerY);

最佳答案

使用 scanf_s 的解决方案很棘手:

char playerX;
int playerY;

if (scanf_s("%c%d", &playerX, (size_t)1, &playerY) == 2) {
/* input parsed correctly */
/* input stopped after the last digit in playerY */
/* You cannot limit the number of digits this way */
} else {
/* end of file or missing number */
/* input stopped before the offending character */
}

scanf_s 对于 scanf 的许多缺点来说是一个糟糕的修复。对于 cs[ 格式,必须在每个指针参数之后传递数组大小。但此大小必须作为 rsize_t 传递,它与具有最大值限制的 size_t 相同。传递 1 是完全错误的,因为 1 是一个 int 并且 scanf_s 接受可变数量的参数,因此不自动转换额外的参数。如果在 intsize_t 大小不同的体系结构(例如 64 位 Windows、Linux 和 OS/X)上,如果会以神秘的方式失败。

您可以通过提高编译器的警告级别来避免此类微妙问题。 gcc -Wall -Werrorclang -Wall -Werror 是一个好的开始。永远不要忽略这些有用的警告,如果您不理解它们,您可能不知道您的代码到底做了什么。

除非您的编码规则或编译器强制要求 scanf_s,否则使用 scanf 会更简单,并且对于此格式同样安全:

if (scanf("%c%d", &playerX, &playerY) == 2) ...

关于c - 使用 scanf 读取无分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29477986/

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