Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
formatted data
string
sprintf

Storing formatted data using sprintf( ) in C

Educative Answers Team

In C, sprintf(), or string print formatted, is used to store formatted data to a string.

Syntax

The general syntax of sprintf() is:

int sprintf (char *str, const char *format.. );

Parameters

  • str: Pointer to the array where the string is to be stored

  • format: This contains the data to be printed, written in a particular format using format specifiers

A format specifier is a unique set of characters which is used to format the data being read in a certain way.

The format specifier follows the following prototype:

 %[flags][width][.precision][length]specifier
svg viewer

Return Value

If the function successfully executes, it returns the total number of characters stored in the string, excluding the null character at the end of the string.

If an error occurs, a negative number is returned.

Example

The following example will help clarify the use of the sprintf() function:

Suppose we wish to store values of different data types in a string. We will proceed as follows:

#include<stdio.h>

int main() {
  
  char string[100] = {'\0'};
  char str[10] = "Today is ";
  int date = 1;
  float time = 3.9339f;
  printf("String before using sprintf():  %s \n", string); // empty string
  sprintf(string, "%s %d %f", str, date, time );
  printf("String after using sprintf(): %s", string); // modified string
  return 0;
}

RELATED TAGS

c
formatted data
string
sprintf
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring