sscanf和尾随字符

ɲeu*_*urɳ 3 c scanf

我正在尝试sscanf用于简单的测试和转换,但我遇到了一个问题,它忽略了字符串中的尾随垃圾.我的示例代码是:

char *arg = "some user input argument";
int val = 0;
if (sscanf(arg, "simple:%d", &val) == 1) {
    opt = SIMPLE;
} else if (strcmp(arg, "none") == 0) {
    opt = NONE;
} else {
    // ERROR!!!
}
Run Code Online (Sandbox Code Playgroud)

这适用于预期的输入,例如:

arg = "simple:2"  --> opt = SIMPLE  val = 2
arg = "none"      --> opt = NONE    val = 0
Run Code Online (Sandbox Code Playgroud)

但我的问题是,在"简单"值之后的尾随字符会被默默忽略

ACTUAL : arg = "simple:2GARBAGE" --> opt = SIMPLE  val = 2
DESIRED: arg = "simple:2GARBAGE" --> ERROR!!!
Run Code Online (Sandbox Code Playgroud)

什么是让sscanf报告尾随垃圾的简单方法?或者,既然我读过"scanf is evil",是否有一个简单的(最好是1-liner)替代方案sscanf来解决上述问题?

chu*_*ica 6

sscanf()额外的char.找不到它.

char ch;
// If _nothing_ should follow the `int`
if (sscanf(arg, "simple:%d%c", &val, &ch) == 1) Success();
// or if trailing white-space is OK
if (sscanf(arg, "simple:%d %c", &val, &ch) == 1) Success();
Run Code Online (Sandbox Code Playgroud)

另一个惯用解决方案使用 %n

int n;
// If _nothing_ should follow the `int`
if (sscanf(arg, "simple:%d%n", &val, &n) == 1 && arg[n] == '\0') Success();
// or if trailing white-space is OK
if (sscanf(arg, "simple:%d %n", &val, &n) == 1 && arg[n] == '\0') Success();
Run Code Online (Sandbox Code Playgroud)