c - sscanf 和尾随字符

标签 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!!!
}

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

arg = "simple:2"  --> opt = SIMPLE  val = 2
arg = "none"      --> opt = NONE    val = 0

但我的问题是“simple”值之后的尾随字符被默默忽略

ACTUAL : arg = "simple:2GARBAGE" --> opt = SIMPLE  val = 2
DESIRED: arg = "simple:2GARBAGE" --> ERROR!!!

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

最佳答案

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();

另一个惯用的解决方案使用 %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();

关于c - sscanf 和尾随字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21888078/

相关文章:

c - 有什么理由在 fgets+sscanf 上使用 scanf 或 fscanf

c - 为什么我的程序不能用于大型数组?

C++ Apache2 模块未加载

c++ - Eclipse CDT 显示一些错误,但项目已成功构建

c - 第一个 scanf ("%s") 在使用第二个 scanf ("%s") 时中断,读取 0

c - getc 和 fscanf 之间的区别

c - scanf()将新行char留在缓冲区中

c - 如何使用动态内存分配将元素分配给矩阵?

c - 使用按位运算交换字符串

c - 使用 scanf 的验证检查在循环内不起作用