Get number of characters read by sscanf?

后端 未结 2 1017
有刺的猬
有刺的猬 2020-12-03 04:21

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

// char* expression;
         


        
2条回答
  •  日久生厌
    2020-12-03 05:21

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

提交回复
热议问题