top of page

Understand C++ getline() for Better Input Handling

In C++ programming, effectively managing user input is essential. It opens the door to creating interactive and dynamic applications. Meet getline(), a potent tool at your disposal. The getline() function was introduced in C++ to provide a robust and flexible way to read input from the user or a file. Prior to getline(), the standard cin or other input methods had limitations when dealing with text input, particularly when handling strings with spaces or special characters.


In this article, we'll decode C++ getline() by exploring its purpose, applications, and tips for smooth input handling.


Let's begin!


Table of Contents:

Advantages of C++ getline()

Limitations of C++ getline()

Syntax

Return Value

Read a single line of input

Read multiple lines of input

Read a line of input with a delimiter

Read a line of input from a file


What is C++ getline?

The getline() function in C++ is a standard library function that is used to read a line of text from an input stream. The getline() function can be used to read a line of text from a file, from the console, or from any other input stream.


The C++ getline() function returns a reference to the input stream stream. If the line of text was successfully read, the return value is the same as the input stream stream. If an error occurs, the return value is a reference to a failed bit-set input stream.


C++ getline() was designed to address these limitations by allowing the program to read an entire line of text, including spaces and special characters, from the input stream (such as the keyboard or a file) and store it as a string. This made it much easier to handle and process textual input in C++ programs, especially for scenarios where users might enter multi-word phrases or sentences.


Advantages of C++ getline():

Here are the advantages of using C++ getline() over other string input functions:

  1. Can be used to read a line of text from different sources such as files, consoles, and other input streams.

  2. Syntax is easy to use and understand.

  3. Efficient function. It does not waste any memory.

  4. It can handle errors gracefully and it does not crash the program.

Here are some of the cases when you should use getline() in C++:

  • When you need to read a line of text from the user.

  • When you need to read a multi-word or multi-line input.

  • When you need to read a string that may contain spaces or other delimiters.

You should not use C++ getline() when you need to read a single word or character. In these cases, you can use the cin >> operator.


Limitations of getline()

Here are some of the limitations of the getline() function in C++:

  • It does not ignore leading whitespace characters. This means that if the user enters a line of text that starts with whitespace characters, the getline() function will still read those characters.

  • It does not handle newline characters at the end of the input stream gracefully. If the user enters a line of text that ends with a newline character, the getline() function will read the newline character and then return an empty string.

  • It can be slow for large strings. The getline() function has to read the entire line of text into a buffer before it can return. This can be slow for large strings.

Here are some ways to work around these limitations:

  • You can use the std::cin.ignore() function to ignore leading whitespace characters before calling the getline() function.

  • You can use the std::getline() function with a delimiter character to handle newline characters at the end of the input stream gracefully.

  • You can use a different function, such as the std::stringstream class, to read large strings more efficiently.


Syntax

Below is the syntax of C++ getline:

std::getline(std::istream& stream, std::string& str, char delimiter);

The C++ getline() function has three parameters:

  • stream: This is the input stream from which the line of text will be read. It can be a file stream, a console stream, or any other input stream.

  • str: This is the string object that will be used to store the line of text.

  • delimiter: This is the character that will be used to delimit the end of the line. If this parameter is omitted, the default delimiter is the newline character (\n).


Return value

The C++ getline() function returns a boolean value. The return value is true if the line of text was successfully read, and false if an error occurred.


Working of getline()

The getline() function in C++ works by reading characters from an input stream until it encounters a delimiter. The delimiter is a character that tells the getline() function to stop reading.

Input stream:   
    "This is a line of text."  

getline()   
    "This is"   
    "a line"   
    "of text." 

In this example, the getline() function reads the characters "This is" from the input stream. When it encounters the newline character (\n), it stops reading and returns.


The C++ getline() function can also be used to read a line of text that ends with a delimiter other than the newline character. To do this, you can pass the delimiter character as the second parameter to the getline() function.


For example, the following code reads a line of text that ends with a space character:

string line;  

getline(cin, line, ' '); 

In this example, the getline() function reads the characters "This is a" from the input stream. When it encounters the space character, it stops reading and returns.


When the C++ getline() function reaches the end of the stream, it returns an empty string. This means that the getline() function has not read any characters from the stream.


The difference between getline() and other string input functions

The getline() function and the cin >> str operator are both used to read strings from an input stream in C++. However, there are some key differences between the two.

Features

C++ getline()

cin >> str

Reads

The getline() function reads a line of text from the input stream, up to and including the newline character (\n).

The cin >> str operator reads a single word from the input stream. If the word contains a space character, the cin >> str operator will only read the first word up to the space character.

Delimiter Character

The getline() function allows you to specify a delimiter character. This is a character that tells the getline() function to stop reading.

The cin >> str operator does not allow you to specify a delimiter character.

Syntax

getline (cin, line)

cin >> name;

Here are some other string input functions in C++ that can be compared with getline():

  • fgets(): This function reads a line of text from a file. It is similar to C++ getline(), but it does not allow you to specify a delimiter character.

  • gets(): This function is a legacy function that is no longer recommended for use. It is similar to fgets(), but it does not have any bounds checking. This means that it is possible to read past the end of the buffer, which can lead to memory corruption.


Examples

Here are some examples of how to use the C++ getline() function:


Example 1: Reading a single line of input

The following code reads a single line of input from the standard input stream and stores it in a string object:

#include <iostream>
#include <string>

using namespace std;  

int main() {   
    string line;    
    
    // Read a line of input.   
    getline(cin, line);    
    
    // Print the line of input.
    cout << "This is an example of single line of input" << line << endl;    
    return 0; 
} 

Output:

C++ getline() -  read single line of input

Example 2: Reading multiple lines of input

The following code reads multiple lines of input from the standard input stream and stores them in a vector of strings:

#include <iostream>
#include <string>
#include <vector>

using namespace std;  

int main() {   
    vector<string> lines;    
    
    // Read multiple lines of input.
    while (true) {     
        string line;     
        getline(cin, line);      
        
        if (line.empty()) {       
            break;     
        }      
        lines.push_back(line);   
    }    
    
    // Print the lines of input.
    for (string line : lines) {     
        cout << line << endl;   
    }    
    return 0; 
} 

Output:

C++ getline() -  read multiple lines of input

Example 3: Reading a line of input with a delimiter

The following code reads a line of input that ends with a space character from the standard input stream and stores it in a string object:

#include <iostream>
#include <string>

using namespace std;  

int main() {   
    string line;    
    
    // Read a line of input with a space delimiter.   
    getline(cin, line, ' ');    
    
    // Print the line of input.
    cout << line << endl;    
    
    return 0; 
} 

Example 4: Reading a line of input from a file

The following code reads a line of input from a file and stores it in a string object:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;  
int main() {   
    string line;   
    ifstream file("myfile.txt");    
    
    // Read a line of input from the file.   
    getline(file, line);    
    
    // Print the line of input.
    cout << line << endl;    
    
    file.close();    
    
    return 0; 
}

How to use C++ getline() to read a line of text which includes Whitespace Characters

The C++ getline() function can be used to read a line of text that includes whitespace characters by specifying a delimiter character. The delimiter character is the character that will be used to delimit the end of the line. However, we can specify any other character as the delimiter character.


For example, the following code will read a line of text from the console that includes whitespace characters:

std::cout << "Enter a line of text: "; 
std::string line; 
std::getline(std::cin, line, ' '); 

In this code, the delimiter character is the space character (). This means that the getline() function will read a line of text up to the first space character. Any whitespace characters that come before the space character will be included in the output.


How to use getline() in conjunction with other functions

The C++ getline() function can be used in conjunction with other functions, such as the strtok() function, to parse a line of text into tokens. The strtok() function is used to break a string into a series of tokens, separated by delimiter characters.


The following code shows how to use the getline() and strtok() functions to parse a line of text into tokens:

#include <iostream>
#include <string>
#include <vector>

using namespace std;  

int main() {   
    string line;   v
    ector<string> tokens;    
    
    // Read a line of input.   
    getline(cin, line);    
    
    // Split the line into tokens.
    char *delimiter = " ";   c
    har *token = strtok(line.c_str(), delimiter);    
    
    while (token != NULL) {     
        tokens.push_back(token);     
        token = strtok(NULL, delimiter);   
    }    
    
    // Print the tokens.
    for (string token : tokens) {     
        cout << token << endl;   
    }    
    return 0; 
} 

In this example, the getline() function reads a line of input from the standard input stream and stores it in the line string object. The strtok() function is then used to split the line string into tokens, separated by space characters. The strtok() function returns a pointer to the next token in the string. The NULL pointer is used to indicate the end of the string.


The tokens vector is used to store the tokens. The while loop iterates over the tokens vector and prints each token to the standard output stream.


Conclusion

C++ getline() is a versatile tool that simplifies input handling, making it especially useful for reading and processing lines of text, whether from user input or files. By mastering its usage and incorporating it into your C++ programs, you can enhance the robustness and user-friendliness of your applications. So, embrace getline() as a valuable asset in your programming toolkit, and let it streamline your input management tasks.


bottom of page