fgets() and gets() in C


fgets()

The function fgets() is used to read the string till the new line character. It checks array bound and it is safe too.

Here is the syntax of fgets() in C language,

char *fgets(char *string, int value, FILE *stream)

Here,

string − This is a pointer to the array of char.

value − The number of characters to be read.

stream − This is a pointer to a file object.

Here is an example of fgets() in C language,

Example

 Live Demo

#include <stdio.h>
#define FUNC 8
int main() {
   char b[FUNC];
   fgets(b, FUNC, stdin);
   printf("The string is: %s
", b);    return 0; }

Output

The input string is “Hello World!” in stdin stream.

The string is: Hello W

In the above program, an array of char type is declared. The function fgets() reads the characters till the given number from STDIN stream.

char b[FUNC];
fgets(b, FUNC, stdin);

gets()

The function gets() is used to read the string from standard input device. It does not check array bound and it is insecure too.

Here is the syntax of gets() in C language,

char *gets(char *string);

Here,

string − This is a pointer to the array of char.

Here is an example of gets() in C language,

Example

#include <stdio.h>
#include <string.h>
int main() {
   char s[100];
   int i;
   printf("
Enter a string : ");    gets(s);    for (i = 0; s[i]!='\0'; i++) {       if(s[i] >= 'a' && s[i] <= 'z') {          s[i] = s[i] - 32;       }    }    printf("
String in Upper Case = %s", s);    return 0; }

Output

Enter a string : hello world!
String in Upper Case = HELLO WORLD!

In the above program, the string s of char array is converted into upper case string. The function gets() is used to read the string from the stdin stream.

char s[100];
int i;
printf("
Enter a string : "); gets(s);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements