236 Programming and Data Structures
7.9 THE sscanf () AND sp rin tf () FUNCTIONS
a) sscanf () The sscanf () function allows to read characters from a character array and writes them
to another array.
This function is similar to scan f () but instead from standard input it reads data from an array.
7.40 Write a program to read string from a character array.
# include <stdio.h>
# include <canio.h>
void main ()
{
char i n [10] ,out[10];
clrsc r () ;
gets(in);
sscanf (in,”% s"j>ut);
printf ("% sn ",out);
}
Q V m i L
HELLO
HELLO
Explanation In the above program two character arrays in [10] and out [10] are declared. Thegets
() function reads the string through the terminal and it is stored in the array in [ ]. Till this time the
o u t[ ] array is empty. The sscanf () function reads characters from array in [ ] and assignes it to
array out [ ]. Thus, both the arrays contain the same string. At the end the p r i n t f () function
displays the contents of array out [ ] .
7.41 Write a program to read integers in character array, convert and assign them to integer
variable using sscanf () function.
# include <stdio.h>
# include <conio.h>
void main ()
{
int *x;
char in [10] ;
c lrsc r ();
printf (" n Enter Integers: " ) ;
gets(in);
sscanf ( in, "% d",x);
printf (" n Value of int x : % d "*x );
getcheO;
I
OUTPUT:
Enter Integers: 123
Value of int x : 123
Explanation In the above program integer is read and stored in the character array in [ ] . The
variable 'x' is declared as an integer pointer. The ssc an f () function assigns base address of array
in [ ] to pointer ' x '. The content of pointer 1 x ' is displayed using pointer notation (*).