English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

fgets() and gets() in C

fgets()

This functionfgets()Used to read a string until the newline character. It checks array bounds and is safe.

This isfgets()C language syntax

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

Here,

String-This is a pointer to a char array.

value-Number of characters to read.

Stream-This is a pointer to a file object.

This isfgets()C language example

Example

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

Output result

The input string is "Hello World!" in the standard input stream.

The string is: Hello W

In the above program, a char type array is declared. This functionfgets()Reads characters from the STDIN stream until the specified number. It does not check array bounds.

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

gets()

This functiongets()Used to read a string from the standard input device. It does not check array bounds and is not safe.

This isgets()C language syntax

char *gets(char *string);

Here,

String-This is a pointer to a char array.

This isgets()C language example

Example

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

Output result

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

In the above program, the string s in the char array is converted to uppercase. This functiongets()Used to read a string from the stdin stream.

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