Get number of characters read by sscanf?

天涯浪子 提交于 2019-11-27 13:55:19
hmjd

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

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

Description for format specifier n from the C99 standard:

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.

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'. */
}
int i, j, k;
char s[20];

if (sscanf(somevar, "%d %19s %d%n", &i, s, &j, &k) != 3)
    ...something went wrong...

The variable k contains the character count up to the point where the end of the integer stored in j was scanned.

Note that the %n is not counted in the successful conversions. You can use %n several times in the format string if you need to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!