Archive for August, 2008


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.. 🙂

Being kind is more important than being right

for https://vctipsplusplus.wordpress.com/

BijU

Advertisements

Thanks to strrchr() !!

hi all,

have you ever tried the function strrchr() ? 🙂 which helped me today during my coding..
let me explain my situation.
I have a string like this 172.16.2.24,2080 (This is a combination of ip address and port number 🙂 )
I want to extract the port number alone from the string. too simple .. right.. 🙂
but I searched some string functions for doing the job.
while going through MSDN i got this function.

and done the job very simple like this…

    int ch = ',';
    char* szPort = strrchr(szIPAddress,ch);
    szPort+= 1;
    MessageBox(NULL,szPort,"Caption",0);

we are born to live, not to exist

for https://vctipsplusplus.wordpress.com/

BijU