使用scanf读取没有分隔符

时间:2015-04-06 19:14:05

标签: c

来自用户的示例输入:

A10

尝试阅读此输入

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

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

编辑:我测试了这个,它只是崩溃了。

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

1 个答案:

答案 0 :(得分:1)

使用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是完全错误的,因为1intscanf_s采用可变数量的参数,因此不会自动转换额外的参数。如果在intsize_t大小不同的架构上以神秘的方式失败,例如64位窗口,Linux和OS / X.

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

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

if (scanf("%c%d", &playerX, &playerY) == 2) ...
相关问题