How To sscanf() or swscanf() ? Example Using delimiters
sscanf() and swscanf() are CRT function using for reading formatted data from a string.
This is an example from MSDN
#include <stdio.h>
void main( void )
{
char tokenstring[] = “15 12 14...”;
char s[81];
char c;
int i;
float fp;
/* Input various data from tokenstring: */
sscanf( tokenstring, “%s”, s );
sscanf( tokenstring, “%c”, &c );
sscanf( tokenstring, “%d”, &i );
sscanf( tokenstring, “%f”, &fp );
/* Output the data read */
printf( “String = %s\n”, s );
printf( “Character = %c\n”, c );
printf( “Integer: = %d\n”, i );
printf( “Real: = %f\n”, fp );
}
Output
String = 15 Character = 1 Integer: = 15 Real: = 15.000000
Simple! right?
Yeh.. Really.
but imagine a situation to read data from this like string.
first:25.5,second,15
(what I mean is that.. its a mixture of : , . etc
)
how can we read those into
first 25.500000 second 15
this form ?
Not a big issue right now. ![]()
a sample code snippet is as follows.
char *tokenstring = "first:25.5,second,15";
int result, i;
double fp;
char o[10], f[10], s[10], t[10];
void main()
{
result = sscanf(tokenstring, "%[^':']:%[^','],%[^','],%s", o, s, t, f);
fp = atof(s);
i = atoi(f);
printf("%s\n %lf\n %s\n %d\n", o, fp, t, i);
}
hey.. look at the output..
the problem is solved..
Note: use the format specifiers as you wish..
Recent Comments