How Sscanf() Splits A String In C
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.
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
- 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 theint
to the corresponding address passed tosscanf
. - 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 tosscanf
- 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 tosscanf
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:
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page