w3resource

C sprintf() function

C library function - sprintf()

The sprintf() function is used to print formatted data to buffer. Any argument-list is converted and put out according to the corresponding format specification in the format-string.

Syntax:

int sprintf(char *buffer, const char *format-string, argument-list)

Parameters:

Name Description
str Pointer to a buffer where the resulting string is stored.
format The format argument is a string containing C language conversion specifications. The conversion specification specifies the notation, alignment, significant digits, field width, and other aspects of the output format. To represent non-printing characters, such as newlines and tabs, the format string may contain escape characters. Below are the details.
additional argument-list Depending on the format string, the function may require additional arguments.

Format strings specify notation, alignment, significant digits, field width, and other aspects of output formats. It can contain ordinary alphanumeric characters; along with escape characters, conversion specifiers, and other characters. Format specifications are made up of a the percent sign (%) followed by one of the following conversion operators, which determine what printf does with its arguments.

Conversion Specifiers:

Specifier Description
%% Print a single % character
%c Convert an int to an unsigned character and print the resulting character
%d or %i Print an int as a signed decimal number
%u Print an unsigned as an unsigned decimal number
%o Print an unsigned as an unsigned octal number
%x Hexadecimal notation (using lowercase letters a-f)
%X Hexadecimal notation (using uppercase letters A-F)
%e Exponential notation (using a lowercase e as in 3.1415e+00)
%E Exponential notation (using an uppercase E as in 3.1415E+00)
%f Print a double using a decimal format like [-]ddd.ddd
%g The more compact of %e or %f, insignificant zeros do not print.
%G Same as g, but using an uppercase E
%s Print the string pointed to by a char *
%p Print a void * argument in hexadecimal (ANSI C only)
%n Store the number of characters printed at this point in the integer pointed to by the int * argument. Nothing is printed. (ANSI C only).

Conversion Flags:

You can control the alignment of the output using any of these optional flags.

Flag Format Example
+ (plus) Always prints a sign character (+ or -). %+7.2d
- (minus) Left-justifies the converted argument in its field. %-7.2d
0 (Zero) Pad with zeros rather than spaces. %07.2d
# (hash)

Use an alternate form for the output. The effect differs depending on the conversion specifier.

  • For o, the precision (described below) is increased so that the first digit printed is a 0
  • For x or X, a non-zero value has a 0x prepended (or 0X for the X specification)
  • For eEfg or G, the result will always contain a decimal point, even if no digits follow it. Additionally, trailing zeros are not removed from numbers formatted with g or G

Conversion width and precision:

By including these options in the format string, you can control the width and precision of the output:

Character Description Example
Field width A digit string specifying the minimum number of digits to be printed. %5f
Precision A digit string including a period (.) specifying the number of digits to be printed to the right of the decimal point. %5.2f

Some conversion operators may also be preceded by a size specification:

  • h indicates that the argument associated with a dioux or X operator is a short or unsigned short.
  • l indicates that the argument associated with a dioux or X operator is a long or unsigned long.
  • L indicates that the argument associated with a eEfg or G operator is a long double (ANSI C only)

Escape sequences in C:

An escape sequence is a series of characters that represents a special character. It begins with a backslash character (\), which indicates that the character(s) that follow the backslash character should be treated in a special way. C uses escape sequences within a format string to print certain special characters. For example \n moves the output position to the beginning of the next line. The following is a list of escape sequences.

Escape sequence Action
\n prints a new line
\b backs up one character
\t moves the output position to the next tab stop
\\ prints a backslash
\" prints a double quote
\' prints a single quote

Return value

  • If successful, returns the number of bytes that are written in the array, not counting the ending null character.

Example: sprintf() function

Following example uses sprintf() to format and print various data.

#include <stdio.h>
 
char buffer[200];
int x, j = 0;
double f;
char *str = "w3resource";
char ch;
 
int main(void)
{
   ch = 'P';
   x = 7;
   f = 12.4567;
 
   /* Format and print various data */
   j = sprintf(buffer, "%s\n", str);
   j += sprintf(buffer+j, "%c\n", ch);
   j += sprintf(buffer+j, "%d\n", x);
   j += sprintf(buffer+j, "%f\n", f);
   printf("%s", buffer);
}

Output:

w3resource
P
7
12.456700

C Programming Code Editor:

Previous C Programming: C fprintf()
Next C Programming: C vfprintf()



Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

How to read the content of a file to a string in C?

char * buffer = 0;
long length;
FILE * f = fopen (filename, "rb");

if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
  {
fread (buffer, 1, length, f);
  }
fclose (f);
}
if (buffer)
{
  // start to process your data / extract strings here...
}

Ref: https://bit.ly/3iCh0vp