how sprintf and sscanf works | applied electronics engineering


how sprintf and sscanf works

By Applied Electronics - Saturday, March 11, 2017 No Comments
Do you know how sprintf() and sscanf() functions work in C programming language? Users are familiar with printf() and scanf() functions but not so much with functions sprintf() and sscanf() functions.

In the tutorial how to display information and read user input in C programming language, we showed how printf() and scanf() functions works. They are called formatted I/O functions. Similarly, sprintf() and sscanf() functions are also formatted I/O functions.

sprintf() and printf() works similarly but there is only one difference. The difference is that sprintf() does not send output to the display, instead, it saves or writes the outputs to array of characters.

Consider the following program.

main( )
   int i = 10 ;
   char ch = 'A' ;
   float a = 3.14 ;
   char str[20] ;

   printf ( "\n%d %c %f", i, ch, a ) ;
   sprintf ( str, "%d %c %f", i, ch, a ) ;

   printf ( "\n%s", str ) ;

In this program the printf( ) prints out the values of i, ch and a on the screen, whereas sprintf( ) stores these values in the character array str. Since the string str is present in memory what is written into str using sprintf( ) doesn’t get displayed on the screen. Once str has been built, its contents can be displayed on the screen. In our program this was achieved by the second printf( ) statement.

Similarly the sscanf() is counterpart of scanf() function. It allows us to read characters from a string and to convert and store them in C variables according to specified formats. The sscanf( ) function comes in handy for in-memory conversion of characters to values. You may find it convenient to read in strings from a file and then extract values from a string by using sscanf( ). The usage of sscanf( ) is same as scanf( ), except that the first argument is the string from which reading is to take place.

See also comparison of while statement in C, python and Matlab programming language.


No Comment to " how sprintf and sscanf works "