Ad

How Sscanf() Splits A String In C

- 1 answer

So basically I have a simple string and i am trying to use sscanf() to split this string and store the values in appropriate variables:

#include<stdio.h>
int main()
{

    int i=10,j;
    char ch = 'A',ch2;
    float a=3.14,b;
    char str[20]="10A3.140000";


    sscanf(str,"%d%c%f",&j,&ch2,&b);
    printf("%d %c %f\n",j,ch2,b);
    return 0;
}

Now my doubt is how exactly sscanf knows where to split the string. Here the value 10 goes in variable j. Character A goes in variable ch2 and 3.140000 goes in variable b. How exactly sscanf is parsing this string and storing values in different variables. It is appreciable if you can explain how exactly sscanf works with any string. I am having a hard time understanding it.

Ad

Answer

This explanation is little over-simplified and there is more than this going on inside the sscanf as the source code is itself more than 3,000 lines of code.

The format specifier mentioned by you in the example is listed below with their corresponding match pattern
%d : [0-9],[-,+]
%f : [0-9],[-,+,.]
%c : [a-z],[A-Z], Other ASCII Characters

Parsing

string parsing

  1. First, for %d, it will first search for [+,-] signs, and if not found then it will look for [0-9] single digits in sequence. As soon as it sees a non-single digit (A = 65) in the string, it will end its search for %d and save the value of the int to the corresponding address passed to sscanf.
  2. Second, for %c, now it will take the next format specifier passed i.e. %c and begin again from the location where it previously stopped. This time it just has to read a single byte from the string and save it to the corresponding address passed to sscanf
  3. Third, for %f, it will first search for [+,-] signs, and if not found it will then look for . and the single digits [0-9]. This continues until it gets something which is not part of the %f, which in this case will be \0. And save it to the corresponding address passed to sscanf

Finally, once everything is completed and the string is split, it returns the total number of arguments parsed. So, it a good programming practice to compare the number of the passed argument list with the returned value.

Reference:

  1. sscanf source code
  2. vfscanf source code
Ad
source: stackoverflow.com
Ad