C Tutorial
gets function is used to collect a string which is a collection of characters terminated by a new line from the standard input stream stdin.
this gets function is part of stdio.h library.
gets function is used here to read the string in console for character array variable and prints the string.
#include<stdio.h> void main() { char websiteurl[100]; printf("\nEnter website url: "); gets(websiteurl); printf("website url is: %s\n", websiteurl); }
Output:
$ cc gets_function.c gets_function.c: In function ‘main’: gets_function.c:7:15: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration] websiteurl = gets(); ^~~~ gets_function.c:7:13: warning: assignment makes pointer from integer without a cast [-Wint-conversion] websiteurl = gets(); ^ /tmp/ccf3r9o5.o: In function `main': gets_function.c:(.text+0x1d): warning: the `gets' function is dangerous and should not be used. $ ./a.out Enter website url: coding pointer. com website url is: coding pointer. com
Output:
$ cc gets_function.c gets_function.c: In function ‘main’: gets_function.c:7:2: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration] gets(websiteurl); ^~~~ /tmp/ccG4qtsI.o: In function `main': gets_function.c:(.text+0x24): warning: the `gets' function is dangerous and should not be used. $ ./a.out Enter website url: www.codingpointer.com
gets function is used here to read the string in console for character pointer variable and prints the string.
#include<stdio.h> void main() { char *websiteurl; printf("\nEnter website url: "); websiteurl = gets(); printf("website url is: %s\n", websiteurl); }
Let us see the exanple to read a string using scanf function.
#includevoid main() { char websiteurl[100]; printf("\nEnter website url: "); scanf("%s", websiteurl); printf("website url is: %s\n", websiteurl); }
Output:
$ cc gets_function.c $ ./a.out Enter website url: www.coding pointer. com website url is: www.coding
Here user eneters string 'www.coding pointer. com', scanf function considers www.coding is one string value, pointer. is another string value and com is the third string value. In output you could see only www.coding as the string value for websiteurl variable.
But if we use gets function instead of scanf function, reads the complete text which is terminated by new line characters.
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page