Welcome to our comprehensive guide on the getline() function in C++! This function is a powerful tool for reading lines from a stream, making it an essential part of many C++ programs. Let's dive in!
getline() Function?The getline() function is used to read lines from a stream, such as a file or the console, into a string. Unlike the standard cin >>, it can read the entire line, including whitespaces and special characters.
š” Pro Tip: The getline() function is particularly useful when you need to read user input with whitespaces or read lines from a file.
The syntax for the getline() function is as follows:
std::getline(istream& is, std::string& str, char delimiter);istream& is: The input stream, usually cin or a file stream.std::string& str: The string where the line is stored.char delimiter: The character used to separate the line from the stream. If not provided, it defaults to the newline character \n.Let's see a simple example of using getline() to read input from the console.
#include <iostream>
#include <string>
int main() {
std::string line;
std::getline(std::cin, line);
std::cout << "You entered: " << line << '\n';
return 0;
}In this example, we read a line from the console into the line string variable and then print the input.
Now let's read lines from a file using getline().
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt");
std::string line;
if (file.is_open()) {
while (std::getline(file, line)) {
std::cout << line << '\n';
}
file.close();
} else {
std::cout << "Unable to open file";
}
return 0;
}In this example, we open a file named example.txt and read each line into the line string variable, printing them out one by one.
What does the `getline()` function do in C++?
By now, you have a good understanding of the getline() function in C++. With this knowledge, you can read user input or lines from a file more effectively in your programs! š
Keep coding, and happy learning! šÆš”šš