Friday, May 27, 2011

sprintf usuage in perl and C

Perl :

sprintf is to produce the formatted string based on the input string.
It is based on sprintf C library routine .

sprintf is useless if  you give the no of digits to be padded less than the no of digits in your variable.As you may see from the below example:


Output will be:456456456

But if you give the no of digits less than the padding digits.In addition to the digits available the remaining will be padded.
$rr=sprintf( "%08d",$dd);

Here 7 zeros are padded with the available digit 2.

The format has many options.In this case we round the digits to 3 decimal point.


C language:
sprintf has a provision to save the formatted string in the syntax itself.

SYNTAX:sprintf(saved string ,format,string to be formatted);

Here the change is the formatted string is saved in the syntax itself,instead of saving through equality condition.

#include <stdio.h>int main ()
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a %d char long string\n",buffer,n);
  return 0;

[5 plus 3 is 8] is a 13 char long string

No comments:

Post a Comment