HP 3000 Manuals

sprintf [ HP C/iX Library Reference Manual ] MPE/iX 5.0 Documentation


HP C/iX Library Reference Manual

sprintf 

Writes formatted data to a character string in memory.

Syntax 

     #include <stdio.h>
     int sprintf (char *string, const char *format 
                  [,item [,item]...]);

Parameters 

string        A pointer to a buffer in memory where the data is to be
              written.

format        Pointer to a character string defining the format (or the
              character string itself enclosed in double quotes).

item,...      Each item is a variable or expression specifying the data
              to write.  Refer below to descriptions of conversion
              specifications and characters.

Return Values 

>=0           If successful, the number of characters written, not
              counting the terminating null character.

<0            An error occurred.

Description 

The sprintf function enables you to write data to a buffer in formatted
form.  The string parameter is a buffer in memory where the data is
written.  The format parameter is a pointer to a character string (or the
character string itself enclosed in double quotes) which specifies the
format and content of the data to be written.  Each item is a variable or
expression specifying the data to write.

The only difference between sprintf() and printf() is that sprintf()
writes data into a character array, while printf() writes data to stdout,
the standard output device.

The sprintf() format is made up of conversion specifications and literal
characters.  Literal characters are all characters that are not part of a
conversion specification.  Literal characters are written to string 
exactly as they appear in the format.

The sprintf function returns the number of characters written or a
negative value (if an error is returned).

Conversion Specifications 

The following list shows the different components of a conversion
specification in their correct sequence:

   1.  A percent sign (%), which signals the beginning of a conversion
       specification; to output a literal percent sign, you must type two
       percent signs (%%).

   2.  Zero or more flags, which affect the way a value is written (see
       below).

   3.  An optional decimal digit string which specifies a minimum field
       width.

   4.  An optional precision consisting of a dot (.)  followed by a
       decimal digit string.

   5.  An optional l, h, or L indicating that the argument is of an
       alternate type.  When used in conjunction with an integer
       conversion character, an l or h indicates a long or short integer
       argument, respectively.  When used in conjunction with a
       floating-point conversion character, an L indicates a long double
       argument.

   6.  A conversion character, which indicates the type of data to be
       converted and written.

A one-to-one correlation must exist between each specification
encountered and each item in the item list.

The available flags are:

-                     Causes the data to be left-justified within
                      its output field.  Normally, the data is
                      right-justified.

+                     Causes all signed data to begin with a sign (+  or
                      -).  Normally, only negative values have signs.

blank                 Causes a blank to be inserted before a positive
                      signed value.  This is used to line up positive and
                      negative values in columnar data.  Otherwise, the
                      first digit of a positive value is lined up with
                      the negative sign of a negative value.  If the
                      blank and + flags both appear, the blank flag is
                      ignored.

#                     Causes the data to be written in an alternate form.
                      Refer to the descriptions of the conversion
                      characters below for details concerning the effects
                      of this flag.

0                     For d, i, o, u, x, X, e, E, f, g, and G
                      conversions, leading zeros (following any
                      indication of sign or base) are used to pad to the
                      field width.  No space padding is performed.  If
                      the 0 and - flags both appear, the 0 flag is
                      ignored.  The 0 flag is also ignored for d, i, o,
                      u, x, and X conversions if a precision is
                      specified.

A field width, if specified, determines the minimum number of spaces
allocated to the output field for the particular piece of data being
written.  If the data happens to be smaller than the field width, the
data is blank- padded on the left (or on the right, if the - flag is
specified) to fill the field.  If the data is larger than the field 
width, the field width is simply expanded to accommodate the data.  An
insufficient field width never causes data to be truncated.  If no field 
width is specified, the resulting field is made just large enough to hold
the data.

The precision is a value which means different things depending on the
conversion character specified.  Refer to the descriptions of the
conversion characters below for more details.


NOTE A field width or precision may be replaced by an asterisk (*). If so, the next item in the item list is fetched, and its value is used as the field width or precision. The item fetched must be an integer.
Conversion Characters Conversion characters specify the type of data to expect in the item list and cause the data to be formatted and written appropriately. The integer conversion characters are: d, i An integer item is converted to signed decimal. The precision, if given, specifies the minimum number of digits to appear. If the value has fewer digits than that specified by the precision, the value is expanded with leading zeros. The default precision is 1. A null string results if a zero value is written with a zero precision. The # flag has no effect. u An integer item is converted to unsigned decimal. The effects of the precision and the # flag are the same as for d. o An integer item is converted to unsigned octal. The # flag, if specified, causes the precision to be expanded, and the octal value is written with a leading zero (a C convention). The precision behaves the same as in d above, except that writing a zero value with a zero precision results in only the leading zero being written, if the # flag is specified. x An integer item is converted to hexadecimal. The letters abcdef are used in writing hexadecimal values. The # flag, if specified, causes the precision to be expanded, and the hexadecimal value is written with a leading "0x" (a C convention). The precision behaves as in d above, except that writing a zero value with a zero precision results in only the leading "0x" being written, if the # flag is specified. X Same as x above, except that the letters ABCDEF are used to write the hexadecimal value, and the # flag causes the value to be written with a leading "0X". The character conversion characters are as follows: c The character specified by the char item is written. The precision is meaningless, and the # flag has no effect. s The string pointed to by the character pointer item is written. If a precision is specified, characters from the string are written until the number of characters indicated by the precision is reached, or until a null character is encountered, whichever comes first. If the precision is omitted, all characters up to the first null character are written. The # flag has no effect. The floating-point conversion characters are: f The float or double item is converted to decimal notation in style f; that is, in the form [-]ddd.ddd where the number of digits after the decimal point is equal to the precision. If no precision is specified, six digits are written after the decimal point. If the precision is explicitly zero, the decimal point is eliminated entirely. If the # flag is specified, a decimal point always appears, even if no digits follow the decimal point. e The float or double item is converted to scientific notation in style e; that is, in the form [-]d.ddde+-ddd where there is always one digit before the decimal point. The number of digits after the decimal point is equal to the precision. If no precision is given, six digits are written after the decimal point. If the precision is explicitly zero, the decimal point is eliminated entirely. The exponent always contains exactly three digits. If the # flag is specified, the result always contains a decimal point, even if no digits follow the decimal point. E Same as e above, except that E is used to introduce the exponent instead of e (style E). g The float or double item is converted to either style f or style e, depending on the size of the exponent. If the exponent resulting from the conversion is less than -4 or greater than the precision, style e is used. Otherwise, style f is used. The precision specifies the number of significant digits. Trailing zeros are removed from the result, and a decimal point appears only if it is followed by a digit. If the # flag is specified, the result always has a decimal point, even if no digits follow the decimal point, and trailing zeros are not removed. G Same as the g conversion above, except that style E is used instead of style e. Other conversion characters are: p The argument is a pointer to void. The value of the pointer is converted to a sequence of printable characters. n The argument is a pointer to an integer into which is written the number of characters written to the output stream so far by this call to fprintf(). No argument is converted. % A % is written. No argument is converted. The complete conversion specification is &%&%. The items in the item list may be variable names or expressions. Note that, with the exception of the s conversion, pointers are not required in the item list. If the s conversion is used, a pointer to a character string must be specified. Example The following program formats data. A user enters data and that data is reformatted into a string, which is passed along to another program, such as a database maintainer. The string contains the data that the user entered, but in a form using strict field widths for the various pieces of data. The database program might require these field widths to be processed correctly, and you need not require the user to enter the data with the field widths. Users can enter data in a convenient form without the fixed field restrictions imposed by the database. #include <stdio.h> main() { char name[31], prof[31], hdate[7], curve[3], string[81]; char *format = "%30s%2d%30s%6ld%6s%2d%2s"; int age, rank; long salary; /* start asking questions */ printf("\nName (30 chars max): "); gets(name); while(name[0] != ']') { printf("Age: "); scanf("%d%*c", &age); printf("Job title (30 chars max): "); gets(prof); printf("Salary (6 digits max, no comma): "); scanf("%D%*c", &salary); printf("Hire date (numerical MMDDYY): "); gets(hdate); printf("Percentile ranking (omit \"%%\"): "); scanf("%d%*c", &rank); printf("Pay curve: "); gets(curve); /* format string */ sprintf(string,format,name,age,prof,salary,hdate,rank,curve); printf("\n%s\n", string); /* start next round */ printf("\nName (30 chars max): "); gets(name); } } The program above asks questions about name, age, job title, salary, hire date, ranking, and pay curve. This data is then packed into a 78-character string using the sprintf() function. This program writes the string on your screen, but in an actual working environment, the string would probably be passed directly to the database program. Note that sprintf() function format is specified as an explicit character pointer. When lengthy, unchanging formats are used, this is more convenient than typing the entire format string, especially if the item list is long. See Also setlocale(), putc(), scanf(), ANSI C 4.9.6.5, POSIX.1 8.1


MPE/iX 5.0 Documentation