Home  >  Article  >  Backend Development  >  What is the purpose of sprintf() and sscanf() functions in C language?

What is the purpose of sprintf() and sscanf() functions in C language?

WBOY
WBOYforward
2023-09-16 21:49:111138browse

What is the purpose of sprintf() and sscanf() functions in C language?

sscanf() function

It reads data from a character string.

Syntax

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

String refers to the string of characters to be read from.

Format string is a character string containing some required formatting information.

Var1, var2, etc. represent each input data item.

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

sprintf() function

This function is used Write data into a character string.

Syntax

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

String refers to the string of characters to be written.

A format specifier is a character string that contains some required formatting information.

Var1, var2, etc. represent each input data item.

Example - 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.

sscanf() function example

Live Demo

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

Output

Tutorials
Tutorials Point

sprintf() function example

Live demonstration

#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

adding two numbers 20 and 30 the result is 50

The above is the detailed content of What is the purpose of sprintf() and sscanf() functions in C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete