Library contents

C++ std::getline

std::getline reads characters into a string up to a delimiter and consumes the delimiter. A successful read can produce an empty string.

A simple example

std::getline

  1. Start with Two lines, A then B
  2. Do this Read one line at a time
  3. Result Two records
The line reader allows the first line to be processed before the second.

Syntax

C++ syntax
std::getline(stream, line)
Run this example in C++

Save the program as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Preserve blank records when reading lines

An import can contain a blank record, an empty field or a missing field. Check how the reader represents each case so a user's deliberate blank is not mistaken for the end of the data.

First output line[A]
lesson.cpp
#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::istringstream input("A\n\nB");
    std::string line;
    while (std::getline(input, line)) std::cout << '[' << line << "]\n";
    return 0;
}
Output
[A]
[]
[B]

The blank line still counts as a record. A final line without a newline is delivered once, so testing getline itself keeps the loop aligned with successful reads.

C++ working draft for std::getline

Advertisements

Read a studio sign-in sheet

A rehearsal has two names with a reserved blank row between them. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenAda / blank / Kim
Worked result3

Read a single shift instruction

A shop closes after recording one instruction without a final newline. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenLock door + EOF
Worked result1