getline Function in C |Syntax and Explanation

Before we learn “What is getline() ?” we should understand why the use of getline Function in C came into the picture. In C, we have two main functions to take a string as an input.

  1. gets()
  2. getline()

Both functions can be used to take a string as an input but the question arises that “Why we have two different functions to take a string as an input ?”. Before we talk about the need for two different functions let’s learn some basic terms.

What is a string ?

A string is a sequence of characters terminated by a null character “\0” and enclosed in double-quotes. In other words, a string is a character array in which the last element is a null character “\0”.(Learn Concatenation of string).

example 1)

char S[] =”geekstocode”

getline
string representation in character array

What is getline function in C and why we need it ?

getline() function is a C library function. This function is used to take a string as an input from the input stream i.e Keyboard. getline() is more preferable than gets() also getline() uses the concept of pointers. Let’s learn some interesting facts about getline().

Syntax

size_t getline(char **string, size_t *n, FILE *stream);

  • size_t is an unsigned integral type datatype therefore it can never be negative. It is mainly used for indexing an array and counting objects.
  • **string is a double pointer to the character array. This points to the location of the first character of the character array.
  • *n is a pointer to the variable which stores the size of the array.
  • FILE *stream the stream from where to read the file i.e stdin.
  • getline() returns the number of characters we gave as input.

Program

#include<stdio.h>
#include<stdlib.h>
int main()
{
    char *string; // character array pointer
    
    size_t size = 10; // initial size of char array
    
    string = (char*) malloc (size);//dynamic memory allocation of character array
    
    if(string == NULL)
    {
        printf("unable to allocate memory");
        exit(1);
    }
    else
    {
        char **string_pointer = &string; // double pointer to char array
    
        size_t characters = getline(string_pointer,&size,stdin);
      
        printf("The number of characters getline() read: %zu\n", characters);
        printf("You typed: %s\n",string);
        printf("%lu", );
        return 0;   
    }
  
}

Points to remember

  1. stdio.h header file contains the definition of getline() function.
  2. getline() function takes three parameters and returns the number of characters we gave as an input. The return value is stored in the characters variable which is of size_t type.
  3. malloc() function is used for dynamic memory allocation to a string pointer. Basically, here we have created a dynamic array of size 10 to store the characters.
  4. stdlib.h header file contains the definition of malloc() function.
  5. The condition string == NULL since this error has a very low chance to occur but it’s a programming practice to check.
  6. To print a size_t data type variable we use %zu format specifier in printf().
  7. To print a char array we can use the %s format specifier in printf().
  8. getline() function extracts character from input stream until the newline character encountered.
  9. getline() function adds a newline character at the end of the string.

Working of getline function in C

  • Here we have dynamically allocated an array of size 10 but what if the user enters characters more than the size allocated to the array. The advantage of the use of getline() function is that this function automatically increases the size of the buffer or the size of the array to store the extra characters.
  • This function returns the number of characters it reads from the user input string.

How to use getline() function with static memory allocated array ?

The solution to this problem is very simple as we just need to store the address of the first character of the array in a pointer and need to pass the address of that pointer in the getline() function.

#include<stdio.h>

int main()
{
    char s[10];
    
    char *string = s; // character array pointer
    
    size_t size = 10; // initial size of char array
    
    char **string_pointer = &string; // double pointer to char array

    size_t characters = getline(string_pointer,&size,stdin);
  
    printf("The number of characters getline() read: %zu\n", characters);
    printf("You typed: %s\n",string);
    
    return 0;   
}

Disadvantage

  • Here we have used a static memory allocated array and therefore getline() function can’t expand the size of the array if the user enters input more than the size of the array and hence gives an error.
  • This concludes that it’s better to use dynamic memory allocated array when you are using getline() function.

Let’s solve a very interesting problem on this topic.

Problem Statement

How to use getline() in c when there are blank lines in input?

Now we all know, if we need to read a few sentences from the stream we will prefer to use getline() but we have to be very careful here. As we all know getline() stops reading input from stream once it encountered newline character(“\n”).

let’s see what is the issue with the code written below.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    char *string;
    size_t size = 100;
    string = (char*) malloc(size);
    int t=4;
    char **string_ptr = &string;
    while(t--)
    {
        getline(string_ptr,&size,stdin);
        printf("sentence you typed: %s",string);
    }
}

Input 1

This
is
a
bug

Expected output

sentence you typed: This
sentence you typed: is
sentence you typed: Geeks
sentence you typed: for

Output 1

sentence you typed: This
sentence you typed: is
sentence you typed: Geeks
sentence you typed: for

Here, the program’s output is the same as the expected output, it is because the input has no blank lines but what if the input contains blank lines?

Input 2

This

is 

Geeks

for

Expected output

sentence you typed: This
sentence you typed: is
sentence you typed: Geeks
sentence you typed: for

Output 1

sentence you typed: This
sentence you typed: 
sentence you typed: is 
sentence you typed: 

Here the problem comes as you can clearly see the program’s output doesn’t match the expected output, it is because of the nature of getline() function. As we know getline() function stops reading from the stream if it encountered a newline character and since the program’s input has empty blanks and getline() considered these empty blanks as a newline character so it assigned an empty string to the string pointer. Therefore, the program’s output is totally different from the expected output.

What is the solution to this problem?

Since we cannot change the nature of getline() function therefore we need to add a special condition while taking strings as an input. Let’s code it!!

Note: getline() function adds a newline character at the end of the string. We will use this point to debug our code.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    char *string;
    size_t size = 100;
    string = (char*) malloc(size);
    int t=4;
    char **string_ptr = &string;
    while(t--)
    {
        
        getline(string_ptr,&size,stdin);
        
        while(string[0] == '\n') // important condition
            getline(string_ptr,&size,stdin);
            
        printf("sentence you typed: %s",string);
    }
}

Input 1

This

is 

Geeks

for

Expected output

sentence you typed: This
sentence you typed: is
sentence you typed: Geeks
sentence you typed: for

Output 1

sentence you typed: This
sentence you typed: is 
sentence you typed: Geeks
sentence you typed: for

Code explanation

  1. Since it has been previously mentioned above that the getline() function adds a newline character at the end of the string when a user presses enter button. We also know that the getline() function considers the empty blanks as a newline character, with this fact we added a very important condition.
  2. while(string[0] == ‘\n’) this condition will exclude all the blank space from the input.

How the while loop debug our code?

getline function in C
The flow of while condition

The while loop will make sure that the string which comes out of it will not be a blank space, instead, it will be a valid sentence. It does not matter how many times we give blank space to the input, while loop only ends when it receives a valid sentence. Otherwise, while loop will keep asking for the input from the input stream.

Key Note: It is a good practice to put this while condition before getline() function.

Why getline() not gets() ?

  • C language has two important functions gets() and getline() to take a string as input from the input stream.
  • gets() is considered to be a dangerous function because it does not check the array bound whereas getline() function always checks the array bound before appending the character. Therefore getline() is safer than gets().
  • Use of gets() is considered to be bad programming.
  • The working of both functions is the same, both functions stop reading input from the stream if they encountered a newline character or end of file. With the fact that gets() is risky to use, we ignore it in the programming world.
  • getline() function reads the whole input and adds it to the string and at the end of the string getline() adds a newline character i.e the enter we pressed. Although, gets() does the same it reads the input and adds the input to the string but it ignores the newline character.

Conclusion

  • The power of getline() function in C has made it a secured and error-free function.
  • size_t is an unsigned integral type datatype.
  • gets() is risky to use and we should ignore it in programming.
  • All the advantages and disadvantages have been discussed in this article. Also, the concept of getline() is very important as many input/output questions have been asked by big tech companies.

Hope you find this article on getline function in C useful.

  1. A Good String Editorial
  2. String Anagram
  3. Concatenate Strings
  4. Sort String in CPP
  5. Tripartite String

Leave a Comment

Your email address will not be published. Required fields are marked *