Home > Backend Development > C++ > 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
Release: 2023-09-16 21:49:11
forward
1240 people have browsed it

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,……..)
Copy after login

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…….);
Copy after login

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;
}
Copy after login

Output

Tutorials
Tutorials Point
Copy after login

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;
}
Copy after login

Output

adding two numbers 20 and 30 the result is 50
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template