< Prev
Next >



C sscanf() and sprintf() function




In our last article, we introduced you to the two most commonly used formatted console input/output functions scanf() and printf(). In this article, we are going to explain two more formatted console input/output functions, sscanf() and sprintf().


Formatted functions Description
sscanf()

The sscanf() function reads the values from a char[] array and store each value into variables of matching data type by specifying the matching format specifier.

sprintf()

The sprintf() function reads the one or multiple values specified with their matching format specifiers and store these values in a char[] array.



Let's take a look at the prototype of sscanf() and pprintf() function and explain them with examples in the upcoming section.





In the upcoming example, we are going to use sprintf() function, which reads one or multiple values specified with their matching format specifiers and store these values in a char[] array.

#include<stdio.h>

int main()
{

char target[20];

char name[10] = "Andrea";
char gender  = 'F';
int age = 25;
float height = 1.70;

printf("The name is : %s", name);
printf("\n");
printf("The gender is : %c", gender);
printf("\n");
printf("The age is : %d", age);
printf("\n");
printf("The height is : %f", height);


/* Calling sprintf() function to read multiple variables and store their values in a char[] array i.e. string.*/
sprintf(target, "%s %c %d %f", name, gender, age, height);


printf("\n");
printf("The value in the target string is : %s ", target);

return 0;
}


Output


The name is : Andrea
The gender is : F
The age is : 25
The height is : 1.700000
The value in the target string is : Andrea F 25 1.700000



Program Analysis


As you may see in the code and its output, we have called the sprintf() function, which linearly reads multiple values by specifying the matching format specifier with their variable names and stores each all these values in a char[] array named target.




Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter




< Prev
Next >
< scanf() and printf() function
Unformatted Console I/O functions >

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page

Notifications



Please check our latest addition

PYTHON