Skip to content

Read Whole Lines

The Course
•
35 min study

Until now every task lived in the source code. To plan a different week you had to edit and recompile the program. A real planner reads its tasks as data: you type them, or paste them from a file, and the same program handles any list. That data arrives through standard input, which C++ exposes as the stream std::cin.

Standard input is a stream of characters. There are no "records" in it, just characters and newline characters, until your program decides how to split them up. The safest first step is to read one whole line at a time. std::getline(std::cin, line) reads characters up to the next newline, stores them in line without the newline, and reports whether it succeeded. In this browser, fill the input box before pressing Run; the program cannot pause and wait for you to type.

Predict and run

The input box for this example is empty.

Predict before running C++
#include <iostream>
#include <string>

int main() {
    std::string line;
    if (std::getline(std::cin, line)) {
        std::cout << "Read: " << line << "\n";
    } else {
        std::cout << "No input\n";
    }
    return 0;
}
Check your prediction
Text
No input

std::getline returns the stream itself, and a stream used as a condition is true only if the last read succeeded. With nothing supplied, the stream reached end-of-file at once, the read failed, and the else branch ran. Now type Read chapter in the input box and run again, then try a single blank line. The blank line prints Read: with nothing after it: a blank line is a successful read of an empty string, which is different from no input at all.

Test input without typing

Typing into the input box for every experiment gets slow, and the course's automatic checks cannot type at all. A string stream, std::istringstream from <sstream>, is a stream that reads from a string you supply. It behaves like std::cin for reading, so you can test input code with fixed text. You will use it heavily in the next lesson.

Words versus lines C++
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::istringstream words("Read chapter\n");
    std::string word;
    words >> word;
    std::cout << "[" << word << "]\n";

    std::istringstream lines("Read chapter\n");
    std::string line;
    std::getline(lines, line);
    std::cout << "[" << line << "]\n";
    return 0;
}
Text
[Read]
[Read chapter]

>> into a string skips leading whitespace and then stops at the next space, so it reads one word. std::getline keeps everything up to the newline, spaces included. A task title like Read chapter has a space in it, which is why the planner reads whole lines.

Read every line

To process all the input, put std::getline in a while condition. Each successful read runs the body once; the first failed read, at end-of-file, ends the loop.

Count lines until end-of-file C++
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::istringstream input("Read chapter\n\nReview notes");
    std::string line;
    int count = 0;
    while (std::getline(input, line)) {
        ++count;
        std::cout << count << ": [" << line << "]\n";
    }
    std::cout << "Lines: " << count << "\n";
    return 0;
}
Text
1: [Read chapter]
2: []
3: [Review notes]
Lines: 3

Three details matter. The blank second line was a successful read, so it counted. The last line had no newline after it, and getline still read it; end-of-file ends a line just like a newline does. And the loop tests the read, not the string: checking line.empty() instead would stop at the blank line and lose everything after it.

Reading whole lines first is also how a program stays robust. If one line is malformed, you can reject that line and carry on with the next, instead of leaving the stream confused halfway through a record. The planner does exactly this.

Practice

Exercise

Your turn

Write void count_lines(std::istream& input, int& lines, int& blank) that reads every line from input, counting all lines in lines and empty lines in blank. In main, call it with a string stream holding "Read chapter\n\nReview notes\n" and print:

  • Lines: 3
  • Blank: 1

Then pass std::cin instead, fill the input box, and check empty input, which should give two zeros.

Your workspace C++
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::istringstream sample("Read chapter\n\nReview notes\n");
    // Write count_lines above main and call it with sample.
    return 0;
}
Read chapter Review notes
Hint 1: the idea

A stream is passed by reference, because reading changes its position and a stream cannot be copied. std::istream& accepts both std::cin and a string stream.

Hint 2: a first step

Start both counters at 0 and use while (std::getline(input, line)). Inside, increase lines, and increase blank when line.empty().

Show one solution
Run the solution C++
#include <iostream>
#include <sstream>
#include <string>

void count_lines(std::istream& input, int& lines, int& blank) {
    lines = 0;
    blank = 0;
    std::string line;
    while (std::getline(input, line)) {
        ++lines;
        if (line.empty()) {
            ++blank;
        }
    }
}

int main() {
    std::istringstream sample("Read chapter\n\nReview notes\n");
    int lines = 0;
    int blank = 0;
    count_lines(sample, lines, blank);
    std::cout << "Lines: " << lines << "\n";
    std::cout << "Blank: " << blank << "\n";
    return 0;
}
Text
Lines: 3
Blank: 1

The loop condition is the read itself, so a blank line counts and is examined instead of stopping the loop. The final newline in the sample does not create a fourth, empty line: after it, the next read hits end-of-file and fails. Because the function takes std::istream&, the same code reads from a test string or from real input. Next you will turn a line of text into a number and reject text that only looks like one.

Was this article helpful?

Your response is saved on this device.