c - 获取 sscanf 读取的字符数?

标签 c string-parsing scanf

我正在解析一个字符串 (a char*) 并且我正在使用 sscanf 将字符串中的数字解析为 double 值,如下所示:

// char* expression;
double value = 0;
sscanf(expression, "%lf", &value);

这很好用,但我想继续通过常规方式解析字符串。我需要知道 sscanf 已经解析了多少字符,以便我可以从新的偏移量恢复手动解析。

显然,最简单的方法是以某种方式计算 sscanf 解析的字符数,但如果没有简单的方法来做到这一点,我愿意接受替代方案双解析选项。不过,我目前正在使用 sscanf,因为它快速、简单且可读。无论哪种方式,我只需要一种方法来评估 double 并在它之后继续解析。

最佳答案

您可以使用格式说明符 %n 并为 sscanf() 提供额外的 int * 参数:

int pos;
sscanf(expression, "%lf%n", &value, &pos);

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.

始终检查 sscanf() 的返回值以确保已进行赋值,并且后续代码不会错误地处理值未更改的变量:

/* Number of assignments made is returned,
   which in this case must be 1. */
if (1 == sscanf(expression, "%lf%n", &value, &pos))
{
    /* Use 'value' and 'pos'. */
}

关于c - 获取 sscanf 读取的字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13503135/

相关文章:

c - 将静态分配数组的地址获取到结构内的指针中

c - E Balaguruswamy 书第 1 章主题子例程第 3 版中的 C 代码错误

c - 避免与 C (C99) 中的枚举发生名称冲突

c++ - rdbuf 对比 getline 对比 ">>"

linux - 在 linux 中设置 _IOFBF 时 stdin 如何工作

c - 平等运算符不工作 `c`

c# - 根据前缀将整数字符串解析为十进制、八进制或十六进制

C#卡路里计数器

c - 程序不会打印 txt 文件中的所有行

c - 数组指针与普通指针的区别