sscanf 未转换的字段不受影响?

sscanf unconverted fields are unaffected?

如果sscanf必须转换一个字段,但失败了,该字段对应的变量是否不受影响?这个问题是在我最近发布的解决方案的评论中提出的:

int validate(int low, int high) {
int s=0;
char buf[128];

    do {
        if (fgets(buf,128,stdin)==0 || sscanf(buf, "%d", &s)!=1 || (s<low || s>high))
            printf("invalid Input, try again:");
    } while (s<low || s>high);
    return s;
}

在此示例中,s 被初始化为零,并且假设它保持为零,而 sscanf 无法从输入转换整数值。这确保在输入无效输入时不会退出循环(假设 low 大于零)。

来自 VC2008 文档“sscanf...returns 成功转换和分配的字段数”这似乎暗示它在内部转换输入并在成功转换后执行分配。这反过来意味着如果 sscanf 无法转换输入,s 不受影响。

If sscanf must convert a field, and it fails, will the field's corresponding variable remain unaffected?

该标准没有明确说明,但它似乎确实遵循了 scanf() 函数族行为的逐步描述。特别是:

Except in the case of a % specifier, the input item [...] is converted to a type appropriate to the conversion specifier. If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure. Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result.

我认为除了说首先转换输入,然后,如果转换成功,它被分配外,很难解释。因此,如果转换失败,则指向的对象不会被修改(通过 that 转换说明符——如果参数重复或它们分别使用别名,则它可能已被较早的对象修改其他)。

因此,我认为您的代码应该按预期运行。