CodeBlanks Logo Icon CodeBlanks

Line reading

Learn to read line by line with getline.

Reading lines with getline

std::getline reads from a file up to the end of a line, not to whitespace. This way you get lines that contain spaces in full.

Example: std::string line; std::getline(in, line);. This reads one line from the in stream and stores it in line. >> would stop at a space; getline stops at a newline and discards it. To process all lines in a file, while (std::getline(in, line)) is common: it loops once per successful read and stops at the end. This is the standard way to process text files line by line.

The getline loop

To process all lines in a file use while (std::getline(in, line)). The loop runs while reading succeeds and stops at the end of the file.

Example: while (std::getline(in, line)) { std::cout << line << "\n"; }. This prints every line in the file one below the other. The loop variable line is refilled on each iteration. Empty lines are also read by getline; in that case line is an empty string. Calling in.close(); after the loop to close the file is a good habit.

Practice Read the first line and print it

The starting code writes two lines to data.txt. Open the file with std::ifstream, read the first line with std::getline and print it with std::cout.

Starter code

main.cpp
#include <iostream>
#include <fstream>
#include <string>

int main() {
    // Prepare the file
    std::ofstream out("data.txt");
    out << "First line\nSecond line";
    out.close();

    // Read the first line and print it

    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ofstream out("data.txt");
    out << "First line\nSecond line";
    out.close();

    std::ifstream in("data.txt");
    std::string line;
    std::getline(in, line);
    std::cout << line;
    return 0;
}

Expected output

First line

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does std::getline(in, line) do?

main.cpp
std::string line;
std::getline(in, line);
  • Reads up to the end of the line Correct answer
  • Reads one number
  • Reads one character
  • Closes the file

Explanation: getline reads up to the end of the line.

2 Match each piece to its role

Term Meaning
std::getline Line reading
>> Word reading
in.close() Closing the file
while (getline(...)) Line loop

3 Complete the getline call

Question
std::____(in, line);
Answer
std::getline(in, line);

Explanation: std::getline reads one line.

All lessons in Intermediate