Use of sprintf and sscanf Functions in C Language



The sscanf() Function

The sscanf() function from the C library reads input from a string and stores the results in specified variables. Each argument must be a pointer to a variable that matches the specified type in the format string.

Syntax

sscanf(string,formatspecifier,&var1,&var2,??..)

Parameters

The following are the parameters for the sscanf() function ?

  • The String refers to the character string to read from.

  • The Format string refers to a character string containing the required formatting information.

  • Var1,var2, etc., represent the individual input data items.

For example, this code extracts two integers from the string and stores them in the variables hours and minutes using sscanf.

sscanf(string,"%d%d",&hours,&minutes);

Example for sscanf() Function

The Following C code uses sscanf() to divide the string "Tutorials Point" into two parts, store them in strings 1 and 2, and print each part on a new line.

#include<stdio.h>
int main() {
   char instring[] = "Tutorials Point";
   char string1[10], string2[10];
   sscanf(instring, "%s %s", string1, string2);
   printf("%s
", string1); printf("%s
", string2); return 0; }

Output

The result is generated as follows ?

Tutorials
Point

The sprintf() Function

The sprintf() function in the C library is similar to printf(), but instead of displaying it on the screen, it saves the string in a user-provided character array.

This function is used to write data to a character string.

Syntax

sprintf(string,format specifier,&var1,&var2??.);

Parameters

The following are the parameters for the sscanf() function ?

  • String refers to a char string to write.

  • Format specifier refers to a char string containing certain required formatting information.

  • Var1,var2, etc., represent the individual input data items.

This code formats a string with the cube and square of two, storing the result in the variable value using sprintf() function.

sprint(value,"cube of two is %d and square of two is %d
", 2*2*2 ,2*2); //value=cube of two is 8 and square of two is 4.

Example for sprintf() Function

In the below example, we are calculating the sum of 20 and 30, storing the result in a string using sprintf(), and prints().

#include <stdio.h>
int main() {
   char value[50];
   int p = 20, q = 30, r;
   r = p + q;
   sprintf(value, "Adding two numbers %d and %d, the result is %d", p, q, r);
   printf("%s", value);
   return 0;
}

Output

The result is obtained as follows ?

Adding two numbers 20 and 30, the result is 50
Updated on: 2024-12-17T14:20:58+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements