Sprintf In C

Example

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

Parameter values

The sprintf function receives various parameter values that are specified as follows -

It serves as the reference to an array of character elements where the final string is saved. This acts as the storage space for inputting the data.

It represents a C string utilized to specify the resulting output, alongside placeholders for the integer parameters to be included within the formatted string. It refers to the string encompassing the content to be appended to the buffer, comprising characters and potentially format specifiers commencing with %.

Now, let's explore some instances of utilizing the sprintf function in the C programming language.

Example1

This serves as an uncomplicated illustration showcasing the application of the sprintf function in the C programming language. In this scenario, we are employing several arguments in conjunction with the sprintf function.

Example

#include <stdio.h>
int main()
{
    char buffer[50];
    int a = 15, b = 25, res;
    res = a + b;
    sprintf(buffer, "The Sum of %d and %d is %d", a, b, res);
    printf("%s", buffer);
    return 0;
}

Output:

Output

The Sum of 15 and 25 is 40

Example2

This is an additional basic illustration showcasing the application of the sprintf function in C programming. Within this instance, there exists a variable named num of type float. The primary purpose of the sprintf function is to convert the numerical data stored in the num variable into a string format, which is then stored within a designated buffer.

Example

#include<stdio.h>
int main() {
  float num = 9.9;
  printf("Before using sprintf(), data is float type: %f\n", num);
  char buffer[50]; //for storing the converted string
  sprintf(buffer, "%f", num);
  printf("After using sprintf() data is string type: %s", buffer);
}

Output:

Output

Before using sprintf(), data is float type: 9.900000
After using sprintf() data is string type: 9.900000

Example3

This serves as another illustration of employing the sprintf function within the C programming language.

Example

#include<stdio.h>
#include <math.h>
int main () {
   char buffer[20];
   sprintf(buffer, "Value of Pi = %f", M_PI);
   printf("%s", buffer);
   return(0);
}

Output:

Output

Value of Pi = 3.141593

Input Required

This code uses input(). Please provide values below: