Reading strings

We have already seen the use of scanf () function and the same can be used with %s format to read a strings. For example:

char name [11];
scanf (“%s”, name);

However the scanf () has got a limitation that it terminates its input on the first white / blank space it encounters. In the above example, if the name is Tulsi das only Tulsi will be read into the array name, since Tulsi is followed by a blank space. In such case two-character array must be before reading the enter text Tulsi das as

scanf (“%s %s”, fname, iname);

Here the string Tulsi is assigned to fname, and das is assigned to iname.

To overcome this difficulty we have a function, similar to scanf () called gets (). Since gets is function, it requires a set of parentheses as shown. There is one more function similar to scanf () called getchar (), which will read only a single charater from the keyboard unlike gets() which can read the entire string until terminated by a return key.

For example,

char a; 
    a= getchar ();

Here getchar () accepts a character from the keyboard and is assigned to the variable a. in the case of gets() the following statements,

char a [80];
gets (a);

when executed, the gets (a) accepts a strings length of 80 characters. The gets () function can be terminated by passing a return key. Let us the usage of getchar () and gets () function through an example program.

Program use of gets () function

#include <stdio.h>
    void main ()
    {
         char name [80];
         printf (“\nEnter name:”);
         gets (name);
         printf (“\nEntered name is: %s\n”, name);
    }

Output

Enter name: Prakash
Entered name is: Prakash



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext