Write formatted data to a string.
#include <stdio.h>
int sprintf( char *buffer, const char *format[[, argument]]...);
int _snprintf( char *buffer, size_t count, const char *format[[, argument]]...);
buffer | Storage location for output | |
format | Format-control string | |
argument | Optional arguments | |
count | Maximum number of bytes to store |
The sprintf function formats and stores a series of characters and values in buffer. Each argument (if any) is converted and output according to the corresponding format specification in the format. The format consists of ordinary characters and has the same form and function as the format argument for the printf function. (See printf for a description of the format and arguments.) A null character is appended to the end of the characters written, but is not counted in the return value.
The _snprintf function differs from sprintf in that it stores no more than count characters to buffer.
Both the sprintf and _snprintf functions return the number of characters stored in buffer, not counting the terminating null character. For _snprintf, if the number of bytes required to store the data exceeds count, then count bytes of data are stored in buffer and –1 is returned.
sprintf
Standards:ANSI, UNIX
16-Bit:DOS, QWIN, WIN
32-Bit:DOS32X
_snprintf
Standards:None
16-Bit:DOS, QWIN, WIN
32-Bit:DOS32X
/* SPRINTF.C: This program uses sprintf to format various data and
* place them in the string named buffer.
*/
#include <stdio.h>
void main( void )
{
char buffer[200], s[] = "computer", c = 'l';
int i = 35, j;
float fp = 1.7320534;
/* Format and print various data: */
j = sprintf( buffer, "\tString: %s\n", s );
j += sprintf( buffer + j, "\tCharacter: %c\n", c );
j += sprintf( buffer + j, "\tInteger: %d\n", i );
j += sprintf( buffer + j, "\tReal: %f\n", fp );
printf( "Output:\n%s\ncharacter count = %d\n", buffer, j );
}
Output:
String: computer
Character: l
Integer: 35
Real: 1.732053
character count = 71