讨论通过的sscanf读取的字符数? [英] Get number of characters read by sscanf?

查看:134
本文介绍了讨论通过的sscanf读取的字符数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我解析一个字符串(的char * )和我使用的sscanf 从数字解析串入双打,就像这样:

I'm parsing a string (a char*) and I'm using sscanf to parse numbers from the string into doubles, like so:

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

这个伟大的工程,但后来我想继续通过常规手段解析字符串。我需要知道多少个字符已被的sscanf 分析,这样我可以从新恢复我手动解析抵消。

This works great, but I would then like to continue parsing the string through conventional means. I need to know how many characters have been parsed by sscanf so that I may resume my manual parsing from the new offset.

显然,最简单的方法就是以某种方式计算字符数的sscanf 解析,但如果没有简单的方法来做到这一点,我的上午的开放替代双解析选项。不过,我目前使用的sscanf ,因为它是快速,简单,易读。无论哪种方式,我只是需要一种方法来评估和双后,继续解析。

Obviously, the easiest way would be to somehow calculate the number of characters that sscanf parses, but if there's no simple way to do that, I am open to alternative double parsing options. However, I'm currently using sscanf because it's fast, simple, and readable. Either way, I just need a way to evaluate the double and continue parsing after it.

推荐答案

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

You can use the format specifier %n and provide an additional int * argument to sscanf():

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

有关格式说明说明 N 从C99标准:

Description for format specifier n from the C99 standard:

没有输入被消耗。 对应​​参数应该是一个指针
  符号整数是成到目前为止此调用到的fscanf 函数
写从输入流中读取的字符数。一个%N的执行指令不增加分配计数在的fscanf 函数执行完毕返回。不转换参数,而是一个被消耗。如果转换规范包括转让燮pressing字符或字段宽度,行为是不确定的。

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(),以确保任务进行了改造,并随后code不误过程变量,其值均持平的返回值:

Always check the return value of sscanf() to ensure that assignments were made, and subsequent code does not mistakenly process variables whose values were unchanged:

/* 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'. */
}

这篇关于讨论通过的sscanf读取的字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆