Chapter Contents

Previous

Next
sprintf

sprintf



Write Formatted Output to a String

Portability: ISO/ANSI C conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
CAUTION
IMPLEMENTATION
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <stdio.h>

int sprintf(char *dest, const char *format,
            var1, var2, ...);


DESCRIPTION

sprintf writes formatted output to the area addressed by dest under the control of the string addressed by format . In the argument list following format , there may be one or more additional arguments whose values are to be formatted and transmitted.

The string pointed to by format is in the same form as that used by fprintf . Refer to the fprintf description for detailed information concerning the formatting conversions.


RETURN VALUE

sprintf returns the number of characters written to the area addressed by dest .


CAUTION

Overruns of the destination area cannot be detected or avoided by sprintf . Thus, you must ensure that the destination area is large enough.


IMPLEMENTATION

sprintf is just like fprintf , with two exceptions:


EXAMPLE

This example transforms a list of names in the form "first, middle, last" into the form "last, first, middle":

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

char *names[] = {
   "John M. Brown",
   "Daniel Lopez",
   "H. Margaret Simmons",
   "Ralph Jones",
   "Harry L. Michaels"
};

main()
{
   char lfm[94];
   char first[31], last[31], middle[31];
   int i, n;

   puts("The names in f-m-l format are:");
   for (i = 0; i < sizeof(names)/sizeof(names[0]); ++i)
      puts(names[i]);
   puts("\nThe names in l-f-m format are:");
   for (i = 0; i < sizeof(names)/sizeof(names[0]); ++i) {
      n = sscanf(names[i], "%s %s %s", first, middle, last);
      if (n != 3){           /* There was no middle name. */
         strcpy(last, middle);
         middle[0] = '\0';
      }
      sprintf(lfm, "%s, %s %s", last, first, middle);
      puts(lfm);
   }
}


RELATED FUNCTIONS

format , fprintf , sprintf , vsprintf


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.