C++

How does getline work in C++?

C++ has many libraries in its general standard library. Three of the libraries involved with getline are the iostream library, the string library, and the fstream library. The iostream library is typically used for input from the keyboard and output to the console (terminal). The string library enables the C++ program to have a string in the form of a data structure, such that each character is in an element, and the characters can be accessed by iterators and with indexes. The fstream library is for input and output to files in the disk.

getline is a member function for each of these three libraries. getline is an input function. Data leaves the keyboard or file, into the program in memory, as a byte sequence. In Western European computer systems, a character is a byte. The sequence of characters first arrives in an area of memory called the buffer. From the buffer, they are either copied or removed one-by-one, into the program that is running.

getline() is one of the functions for extracting the characters from the buffer in memory into the program, which is also in memory. All that is inputting. So, getline() deals with imputing and not outputting. Extraction means the characters are removed from the buffer into the program; they are not copied. The characters are extracted as they arrive. The idea of getline is that getline extracts a whole line from the buffer into the program.

This article deals with getline() for the iostream and string libraries. getline() for files, is normally discussed with fstream, and so fstream with its getline() function, will not be discussed here.

Article Content

getline() and cin

cout and cin are two objects of the iostream class that has already been instantiated and present in the library. Once the iostream class has been included in the C++ program, these objects can be used straight away, without instantiation (or declaration). cout is for sending a text to the terminal, and cin is for receiving a text from the keyboard.

As the user is typing on the keyboard, the characters are echoed at the terminal as well as going into a buffer in memory. As that is happening, cin is waiting. As soon as the user presses the Enter key, cin for the program would take as many words as it was coded to take from the buffer. When the user pressed the Enter key, that was one line. If cin was coded with its getline() member function, then cin would take the whole line into the program.

A line normally ends with the newline character, ‘\n’ (pressing the Enter Key), corresponding to decimal ASCII code 10. There are two getline member functions for cin (or iostream). One extracts a number of consecutive characters, beginning from the first. The number of characters may end in front of the newline character or go past the newline character (‘\n’). For the other overloaded member function, the programmer decides what character the end-of-line should be, and it extracts up to or just before the end-of-line.

basic_istream& getline(char_type* s, streamsize n)

This is a cin member function. The first argument here is an array created by the programmer. It should have at least n cells. n – 1 character will be extracted from the buffer and placed into the array, s. The nth position in the array will receive the NUL character, ‘\0’; and so the array will become a string. So the array, s has to be declared as an array-of-chars. cin.getline() should be coded in the program, where input is expected from the console.

The reader should read and test the following program with the input,

    aaa bbb ccc ddd eee

pressing the Enter Key after, eee:

    #include <iostream>

    using namespace std;

   
    int main()

    {

        cout <<"Enter Words:" <<endl;


        char s[14];


        cin.getline(s, 14);


        for (int i=0; i <15; i++) {

            if (s[i] == '\0')

                break;

            cout <<s[i];

        }

        cout <<endl;


        return 0;

    }

The output is:

    aaa bbb ccc d

Thirteen characters were displayed. The for-loop in the program worked without any problem. This means that the fourteenth position in the array was given, ‘\0’. If the size of the array is bigger than n, the string will still be formed, but it will take a shorter range.

basic_istream& getline(char_type* s, streamsize n, char_type delim)

This member function is similar to the above. However, if n-1 characters occur before the end-of-line character, then n-1 characters will be sent to the array, s. If the newline character occurs before the n-1 characters are reached, then all the lines, up to but not included, the newline character will be sent to the array. The NUL character, ‘\0’ will also be sent to the array as the last character by the program. So, the array length should be estimated, longer than n or longer than the complete line without ‘\n’.

The third argument, delim, is to be ‘\n’. Some other characters can be chosen for delim. In that case, the search can stop before ‘\n’ or go past ‘\n’. For the following program, where the input is,

    aaa bbb ccc ddd eee

all the characters before the Enter Key is pressed are taken:

    #include <iostream>

    using namespace std;

   
    int main()

    {

        cout <<"Enter Words:" <<endl;


        char s[25];


        cin.getline(s, 25, '\n');


        for (int i=0; i <25; i++) {

            if (s[i] == '\0')

                break;

            cout <<s[i];

        }

        cout <<endl;


        return 0;

    }

The output is,

    aaa bbb ccc ddd eee

as expected.

In the following program, 20 characters are sent to the buffer, including ‘\n’. However, only 12 characters are extracted from the buffer because the delimiter, delim is ‘d’. The input is:

    aaa bbb ccc ddd eee

The program is:

    #include <iostream>

    using namespace std;

   
    int main()

    {

        cout <<"Enter Words:" <<endl;


        char s[25];


        cin.getline(s, 25, 'd');


        for (int i=0; i <25; i++) {

            if (s[i] == '\0')

                break;

            cout <<s[i];

        }

        cout <<endl;


        return 0;

    }

The output is:

    aaa bbb ccc

There is an extra space after the last ‘c’, to make it 12 characters.

getline() and String Object

The getline() function can be used to get input from the keyboard and from the disk of files. This section of the article deals with getting input from the keyboard into the program through the cin object. Getting input from a file into the program is not discussed in this article. The string library has four overloaded functions for getline(), paired. These four functions are functions of the library and not member functions of the string class.

basic_istream& getline(basic_istream& is, basic_string& str)

This string library function is similar to the getline function, without the delimiter, delim discussed above. However, instead of sending characters collected to an array, the characters are sent to a string object, str, instantiated from the string class. The “is” argument of this function can be cin. The lengths of the arguments, “is” and str is not estimated or predetermined. This member function also differs from the corresponding one above in that it collects a whole line from the buffer, with cin, without the newline character used in the function. The string library has to be included in the program. The following program illustrates its use with the keyboard input,

    aaa bbb ccc ddd eee

Press the Enter Key after typing, eee. The program is:

    #include <iostream>

    #include <string>

    using namespace std;

   
    int main()

    {

        cout <<"Enter Words:" <<endl;


        string str;


        getline(cin, str);


        for (int i=0; i <25; i++) {

            if (str[i] == '\0')

                break;

            cout <<str[i];

        }

        cout <<endl;


        return 0;

    }

The output is:

    aaa bbb ccc ddd eee

as expected. The total number of characters from the keyboard is 19, excluding ‘\n’. The output is correct because the for-loop iterated 25 times.

basic_istream& getline(basic_istream&& is, basic_string& str)

This function is similar to the above, but emphasizes on moving.

basic_istream& getline(basic_istream& is, basic_string& str, charT delim)

This string library function, which is not a string class member function, is similar to the above function but with a delimiter. However, all characters that occur before the end-of-line character will be sent to the second argument, str. The end-of-line in the buffer is indicated by the third argument character, delim. delim should be ‘\n’. However, the programmer can decide on any other character for the end-of-line.

For the following program, where the input is,

    aaa bbb ccc ddd eee

all the characters before the Enter Key is pressed are taken. The Enter Key results in ‘\n’.

    #include <iostream>

    #include <string>

    using namespace std;

   
    int main()

    {

        cout <<"Enter Words:" <<endl;

        string str;


        getline(cin, str, '\n');


        for (int i=0; i <25; i++) {

            if (str[i] == '\0')

                break;

            cout <<str[i];

        }

        cout <<endl;


        return 0;

    }

The output is:

    aaa bbb ccc ddd eee

In the following program with the same input, the deliiter or end-of-line character is ‘d’:

    #include <iostream>

    #include <string>

    using namespace std;

   
    int main()

    {

        cout <<"Enter Words:" <<endl;

        string str;


        getline(cin, str, 'd');


        for (int i=0; i <25; i++) {

            if (str[i] == '\0')

                break;

            cout <<str[i];

        }

        cout <<endl;


        return 0;

    }

The output is:

    aaa bbb ccc

There is a single space character after the last ‘c’ in the output.

basic_istream& getline(basic_istream&& is, basic_string& str, charT delim)

This function is similar to the above, but emphasizes on moving.

Conclusion

The getline function is used for input. Input can come from the keyboard or from a file. Input data comes as a sequence of characters into a buffer in memory. The programmer can code the getline() function to get the data when they come into the system unit (memory buffer). cin corresponds to the buffer. getline() gets the data in chunks, one chunk per scan. A chuck can be a given number of characters or any number of characters but delimited by the end-of-line character.

The iostream, the string, and the fstream libraries all have the getline() function. With the iostream library, getline() is a member function of the cin object (overloaded). With the string library, getline() is just a function in the library (overloaded); it is not a member function of the string class. In fact, cin is actually an argument of the getline() function of the string library. As for the getline() function in the fstream library, that is discussion, for some other time.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.