使用 sscanf 控制整个字符串

标签 c parsing scanf

我需要在c中解析一个格式为“foo=%d”的字符串,我需要检查格式是否正确并读取int值。

我的初始代码是:

int foo_set = 0;
int foo;
if (sscanf(text, "foo=%d", &foo) == 1)
    foo_set = 1;

但是代码应该拒绝诸如“foo=5$%£”之类的输入。 这段代码行得通吗?

int foo_set = 0;
int foo;
char control;
if (sscanf(text, "foo=%d%c", &foo, &control) == 1)
    foo_set = 1;

使用 control 字符代码检查没有额外的输入。 有没有更好/更正确的方法来做到这一点?

谢谢

最佳答案

使用 %n 格式说明符来确定处理结束的位置并检查它是否与字符串的长度相匹配:

const char* text = "foo=4d";
int pos;
int foo;

if (sscanf(text, "foo=%d%n", &foo, &pos) == 1 &&
    pos == strlen(text))
{
    /* Valid as all of text consumed. */
}

C99 标准中格式说明符 n 的说明:

No input is consumed. The corresponding argument shall be a pointer to signed integer into which is to be written the number of characters read from the input stream so far by this call to the fscanf function. Execution of a %n directive does not increment the assignment count returned at the completion of execution of the fscanf function. No argument is converted, but one is consumed. If the conversion specification includes an assignment suppressing character or a field width, the behavior is undefined.

参见 https://ideone.com/d1rhPf 的演示.

关于使用 sscanf 控制整个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13701657/

相关文章:

c - getchar() 在 c 中不起作用

c - scanf导致C程序崩溃

c++ - 如何隐藏控制台窗口并调出启动画面?

c - 使用函数将文本文件读入结构数组

c - 如何将 char 数组转换为 unsigned int?

python - 函数调用运算符优先级

c - 轻量级且可扩展的 C 编译器前端

c - 使用它时是否可以在不使用 malloc 的情况下增加 char 数组?

regex - 什么是上下文无关语法?

预期输入格式的 C Scanf 输入测试