sprintf

Syntax:

    #include <cstdio>
    int sprintf( char *buffer, const char *format, ... );

The sprintf() function is just like printf(), except that the output is sent to buffer. The return value is the number of characters written. For example:

     char string[50];
     int file_number = 0;
 
     sprintf( string, "file.%d", file_number );
     file_number++;
     output_file = fopen( string, "w" );

Note that sprintf() does the opposite of a function like atoi() – where atoi() converts a string into a number, sprintf() can be used to convert a number into a string. For example, the following code uses sprintf() to convert an integer into a string of characters:

     char result[100];
     int num = 24;
     sprintf( result, "%d", num );

This code is similar, except that it converts a floating-point number into an array of characters:

     char result[100];
     float fnum = 3.14159;
     sprintf( result, "%f", fnum );

Note that this function does not check the bounds of the buffer and therefore creates the risk of a buffer overflow. A secure alternative is snprintf

Related Topics: snprintf, atof, atoi, atol, fprintf, printf