C++ getline() Function

beginner
21 min

C++ getline() Function

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!

What is the 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.

Syntax

The syntax for the getline() function is as follows:

cpp
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.

Example 1: Reading from the Console

Let's see a simple example of using getline() to read input from the console.

cpp
#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.

Example 2: Reading from a File

Now let's read lines from a file using getline().

cpp
#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.

Quiz

Quick Quiz
Question 1 of 1

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! šŸŽÆšŸ’”šŸ“šŸ“š