The fgets()
and gets()
methods in the C language read string values with spaces.
fgets()
reads the data from the given stream until the new line character is read, (val-1) characters are read, or the end of the file is reached. This then stores this data into the string.
str
: It is the pointer to an array of characters that will store the string that is read.val
: It is the count of the characters to be read.stream
: It is a pointer that points to a file object.char*
: It is the character array.char *fgets(char *str, int val, FILE *stream)
In this example, if we input “Educative for learning
,” the output will only be “Educative
.” This is because the fgets()
function has a LIMIT of reading only 10 characters. So, it will only read LIMIT-1, or 9, characters from the input string.
#include <stdio.h>#define LIMIT 10int main(){char str[LIMIT];fgets(str, LIMIT, stdin);printf("str is: %s\n", str);return 0;}
Enter the input below
fgets()
function to read the number of characters defined by the limit and store them into str
.str
.gets()
reads the data from the given stream until the new line character is read, or the end of the file is reached. This then stores this data into the string.
str
: It is the pointer to an array of characters that will store the string that is read.char*
: It is the character array.In this case, defining a size of str
will be of no use. This is because the function reads till the new line character is reached. Moreover, size is not a parameter in this function, unlike in fgets()
.
char * gets ( char * str );
In this example, if we input “Educative for learning
,” the entire string will be stored into str
. This is because the function gets()
function will read the string until the new line character, irrespective of its size.
#include <stdio.h>#define LIMIT 15int main(){char str[LIMIT];gets(str);printf("str is: %s\n", str);return 0;}
Enter the input below
gets()
function to read the number of characters until the new line character, irrespective of limit, and store them into str
.str
.Note: In this case, an
error
might appear. This is because thegets()
function is not ideal to use when no array limit is checked, and it keeps on reading until the new line character.