Different ways to get string as input in C language

By default C language doesn't have a string data type.  But we can use a character array data type which is also considered as string. 

#include <stdio.h>

int main () {
char initial;
scanf ("%c \n", &initial);
printf ("%c \n", initial);
return 0;
}

Consider the above program which gets input of a character and prints that character.  Even if you entered a string as the input, only the first character of the word would be saved to the variable initial.  This is because char data type can only store one letter.

So in order to get more characters we must use a character array.  At this point you may think that we can use a for loop to store the characters to the array.  But some time we may not know the length of the string, so that we cannot stop our for loop on certain time.  That's why we have a special function called "gets()" in C language.

#include <stdio.h>

int main () {
char name[20];
gets (name);
printf ("%s \n", name);
return 0;
}

The above code will get input and stores it in array format in the name variable.  gets() will stop its execution when it detects a return(enter) pressed by the user.

Comments