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.
#include<stdio.h>
int main()
{
char ar[20] = "User M 19 1.85";
char str[10];
char ch;
int i;
float f;
/* Calling sscanf() to read multiple values from a char[] array and store each value in matching variable */
sscanf(ar, "%s %c %d", &str, &ch, &i, &f);
printf("The value in string is : %s ", str);
printf("\n");
printf("The value in char is : %c ", ch);
printf("\n");
printf("The value in int is : %d ", i);
printf("\n");
printf("The value in float is : %f ", f);
sscanf(ar, "%s %c %d", &str, &ch, &i);
return 0;
}
The value in string is : User
The value in char is : M
The value in int is : 19
The value in float is : 1.850000
Advertisement
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;
}
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
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.
< scanf() and printf() function
Unformatted Console I/O functions >
Advertisement
Please subscribe to our social media channels for daily updates.
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement
About us | Contact us | Privacy-policy | Terms
Please Subscribe
© Copyright 2020 Decodejava.com. All Rights Reserved.