scanf & sscanf

Scanf reads the data entered in the standard input. 




To stop reading the characters when 'Enter' is hit, use "%[\n]s" instead of "%s"



What sscanf does ?



Reads data from argument 1 and stores them according to parameter format into the locations given by the additional arguments.

Syntax


int sscanf ( const char * s, const char * format, ...);



Lets be Network Protocol Developer for sometime ;-) 

const char *value = "1926.786.1.4";
printf("value = %s\n",value);
unsigned     int   a, b, c, d,e,f,g,h;
sscanf(value, "%4u.%3u.%3u.%3u \t", &a,&b,&c,&d);
printf("a %d b %d c %d d %d \t",a,b,c,d);

sscanf(value, "%d.%d.%d.%d \t", &e,&f,&g,&h);

printf("e %d f %d g %d h %d \t",e,f,g,h);


In the above example, if the value is "192.168.1.254", this will be read from the first argument value in sscanf. We can split this values as a, b, c & d.

Result 

value = 1926.786.1.4

a 1926 b 786 c 1 d 4    e 1926 f 786 g 1 h 4 

Eg 2 :


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {

int day, year;
char weekday[20], month[20], dtm[100];

strcpy( dtm, "Saturday March 25 1989" );

sscanf( dtm, "%s %s %d  %d", weekday, month, &day, &year );

printf("%s %d, %d = %s\n", month, day, year, weekday );

 
return(0);
}

Result 

March 25, 1989 = Saturday 

How to convert a string to integer ?

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


    int var = 0;

    char *c = "7899";

    sscanf(c, "%d", &var);

    printf("%d", var);


    return;

}


Output:

7899


Difference between scanf and sscanf ?


1. scanf will read the data from standard input.
    sscanf will read the data from argument 1.




(Will be updated if i find more information)

Comments