Updated October 17, 2023
Introduction to C++ getline()
In C++, you can use the standard library function getline() to read input from an input stream, such as the console or a file. This function allows you to read an entire line of text, including spaces and newline characters, and store it as a string. It is helpful for handling user input and text-processing tasks in C++ programs.
Table of Content
- Introduction to C++ getline()
- Syntax
- Why we use getline in C++
- Difference Between get and getline in C++
- Common Errors and Troubleshooting
- Alternatives to getline() in C++
Syntax of C++ getline() function
There are two representations of the getline() function, which differ based on the number of parameters they can accept; in other words, based on the parameters passed to the getline() function, the particular getline() function overloads. Both representations are –
Syntax #1
istream& getline(istream& is, string& str, char delim);
first representation where it accepts three parameters, which are is, str, and delim.
Parameters:
- is: An object of std::istream class that specifies the input stream from where to read the input. It can be std::cin for standard input (keyboard) or a std::ifstream object for reading from files.
- str: The input stream reads and stores the input in a string object. The getline() function will store the characters read up to (but not including) the delimiter character or the end of the stream into this string.
- delim: The delimiter character that tells the function when to stop reading further input. The getline() function reads characters from the input stream until it comes across the specified delimiter or reaches the end of the stream. The “str” string does not save the delimiter character taken from the input stream.
Syntax #2
istream& getline( istream& is, string& str );
Parameters:
- is: An object of std::istream class that specifies the input stream from where to read the input. It can be std::cin for standard input (keyboard) or a std::ifstream object for reading from files.
- str: A string object in which the input will be stored after being read from the input stream. The getline() function will store the characters read up to (but not including) the newline character (‘\n’) or the end of the stream into this string.
In this version of getline(), the newline character (‘\n’) serves as the default delimiter, which means the function will read characters from the input stream until it encounters a newline or reaches the end of the stream. The newline character is extracted from the input stream but not stored in the str string.
Why we use getline in C++
Here are a few practical examples to demonstrate the use of the getline() function in various circumstances.
1. Reading from the Standard Input
The getline() function in C++ is frequently used to read data from the standard input, typically the keyboard.
Code:
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter Your Favourite Sport: ";
std::getline(std::cin, input);
std::cout << "You like to play " << input << std::endl;
return 0;
}
Output:
When running this program, the user will be asked to enter the sports name. After pressing Enter, the user will see the inputted line again after saving it in the input variable.
2. Reading from a File
In machine learning and data analysis tasks, reading data from files for model training or analysis is typical practice. Using C++, the following example shows how to read data from a file:
First, create a file using .txt, for example, Educba.txt, and enter the text you want to display in the output.
Code:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("Educba.txt");
std::string line;
if (file.is_open()) {
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
}
return 0;
}
Output:
This example reads lines from a file called “Educba.txt” using the getline() function. After that, each line is printed to the console. For actions involving files, be sure to add the ifstream header.
3. Custom Delimiter
By default, the getline() method in C++ reads input until a newline character (‘n’). You can define a custom delimiter to stop reading input at a different character or set of characters.
Code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//macro definitions
#define MAX_NAME_LEN 50 // Maximum len of your name can't be more than 50
#define MAX_Course_LEN 30 // Maximum len of your course can't be more than 30
#define MAX_Registration_LEN 60 // Maximum len of your registration can't be more than 60
int main() {
char y_name[MAX_NAME_LEN], y_course[MAX_Course_LEN], registration_y[MAX_Registration_LEN];
cout << "Enter your name: ";
cin.getline (y_name, MAX_NAME_LEN);
cout << "Course you enrolled: ";
cin.getline (y_course, MAX_Course_LEN);
cout << "Registration (press ! to complete): ";
cin.getline (registration_y, MAX_Registration_LEN, '!'); //! is a delimiter
cout << "\nForm Submission:\n"<<'\n';
cout << "Name: " << y_name << endl;
cout << "Course: " << y_course << endl;
cout << "Registration: " << registration_y << endl;
}
Output:
This illustration’s getline() function will read the input until the character (!). The input variable will hold the text that comes before the exclamation mark.
You can change the delimiter to any character or string of characters that suit your needs. For instance, you can specify a longer string as the delimiter or use a comma (,) as the delimiter.
4. Handling Empty Lines
When dealing with input that could have empty lines, it’s essential to think about how to manage them properly. Here’s an illustration of handling empty lines using the getline() function in C++.
Code:
#include <iostream>
#include <string>
int main() {
std::string line;
while (std::getline(std::cin, line)) {
if (line.empty()) {
// Handle empty line
std::cout << "No Input Entered" << std::endl;
} else {
// Process non-empty line
std::cout << "Input Entered: " << line << std::endl;
}
}
return 0;
}
Output:
In this example, when an empty line is detected, the program will output a message indicating No Input Entered. The program will display input Entered with the text you typed for non-empty lines.
You can modify the code to handle empty lines according to your needs. For example, you could skip the empty line or perform additional data processing tasks instead of printing a message.
5. Remove Leading and Trailing Whitespace
Removing any spaces, tabs, or other whitespace characters that appear at a string’s start or end is called removing leading and trailing whitespace.
Code:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
std::string removeLeadingTrailingWhitespace(const std::string& str) {
std::string result = str;
// Remove leading whitespace
result.erase(result.begin(), std::find_if(result.begin(), result.end(), [](int ch) {
return !std::isspace(ch);
}));
// Remove trailing whitespace
result.erase(std::find_if(result.rbegin(), result.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), result.end());
return result;
}
int main() {
std::string input;
std::cout << "Enter Your City: ";
std::getline(std::cin, input);
std::string trimmed = removeLeadingTrailingWhitespace(input);
std::cout << "You Stay in " << trimmed << std::endl;
return 0;
}
Output:
In the above example, there is space at the beginning of New York, but the space gets removed using Remove Leading and Trailing Whitespace.
Removing any leading or trailing whitespace from the string is essential to make it easier to process, validate, and manipulate data accurately. This ensures that we deal only with actual content.
Difference Between get and getline in C++
Common Errors and Troubleshooting
Here are some of the most common errors and how to troubleshoot them:
1. Incorrect Function Signature
Error: Using the incorrect function signature for getline.
Solution: getline contains two signatures: one that reads from std::cin (for keyboard input) and another that reads from files. Make sure you use the correct signature for your use case.
// Reading from stdin (keyboard input)
std::string input;
std::getline(std::cin, input);
// Reading from a file
std::ifstream file("filename.txt");
std::string line;
while (std::getline(file, line)) {
// Process the line
}
2. Forgetting to Include Necessary Headers
Error: The essential headers for getline are not included.
Solution: To use getline, include the <iostream> and <string> headers or <fstream> for file input.
#include <iostream>
#include <string>
// or
#include <fstream>
3. Not Handling Errors
Error: When using getline, failing to check for errors.
Solution: Always inspect the return value of getline. It returns the stream on which it was called, which can be evaluated as a boolean to detect faults.
std::string input;
if (std::getline(std::cin, input)) {
// Input was successful
} else {
// Handle the error
}
4. Dealing with Newline Characters
Error: getline reads and includes newline characters (‘n’) in the string, which may result in unexpected behavior.
Solution: Using the std::getline function, remove the trailing newline character with the erase method or another way.
std::string input;
if (std::getline(std::cin, input)) {
if (!input.empty() && input.back() == '\n') {
input.pop_back(); // Remove the trailing newline character
}
}
5. Buffer Overflow
Error: When reading into a character array, getline does not specify a maximum line length.
Solution: Always specify a buffer size when reading into character arrays to avoid buffer overflow.
char buffer[256];
std::cin.getline(buffer, sizeof(buffer));
6. Using cin.ignore()
Error: Clearing the buffer with cin.ignore() after cin.getline().
Solution: Avoid using cin.ignore() after getline() since getline() already discards the newline character.
std::string input;
std::getline(std::cin, input); // No need for cin.ignore() here
Alternatives to getline() in C++
Here are some commonly used alternatives:
1. Using stream extraction operator (>>)
- One can utilize the stream extraction operator (>>) to read input until it comes across whitespace.
- This method is appropriate for scanning individual words or information with a known format and type.
- Input containing spaces or special characters may need extra attention.
2. Using std::fgets()
- std::fgets() is a C-style function that reads a line of input from a file stream or stdin.
- It deals with the input until it enters a newline character or reaches the maximum number of characters given.
- When working with legacy codebases, std::fgets() might be handy for reading input from files.
3. Using third-party libraries
- Tokenizer: This library offers the flexibility to tokenize input using personalized delimiters for parsing purposes.
- RapidJSON: A JSON parsing library is available that can handle complicated data structures and validate them.
- Poco Libraries: This tool offers different utilities for handling input, such as parsing CSV and XML files.
4. Using string manipulation techniques
- If the input follows a specific format, you can use string manipulation functions (e.g., std::find(), std::substr()) to extract necessary data.
- This method is appropriate when the input format remains consistent and predictable.
5. Creating a custom input parsing function
- You can create a personalized function to manage input parsing and validation based on your needs.
- This approach gives you complete control over how the data parses. You can personalize how you handle errors and how to recover from them.
FAQ’s
Q1. What is the difference between cin and getline() for reading input in C++?
Ans: The “cin” function reads input of different data types like integers, floats, or characters. On the other hand, the “getline()” function reads an entire line of text. When using cin, the reading process terminates at the first whitespace encountered. On the other hand, getline() reads the whole line, including any spaces present.
Q2. Can I use getline() in a loop to read multiple input lines?
Ans: Yes, getline() is commonly used in loops to read multiple input lines until the end of the input stream. You can use it with a while loop to continuously read and process lines until no more input is available.
Q3: Are there any limitations to the size of input getline() can handle?
Ans: When you use getline(), the amount of available memory determines the maximum size of the input. However, using std::string getline() can manage input lines of virtually any size without explicit buffer size restrictions.
Q4: Can I mix input methods in the same program, such as cin >> variable and getline()?
Ans: You can use different input methods in the same program. It’s important to eliminate any remaining newline characters in the input buffer to prevent unexpected results when switching between methods. To clear the buffer before using getline(), you can achieve this by utilizing cin.ignore().
Conclusion
This article emphasizes the significance of comprehending and effectively utilizing the getline() function in C++ to handle text-based input. To ensure accurate input processing, tackling common errors and troubleshooting issues is essential. Getline() is a powerful and versatile tool that allows developers to read text lines from different sources, offering robust input management in C++ programs.
Recommended Articles
We hope that this EDUCBA information on “C++ getline()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.