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
- Start with Two lines, A then B
- Do this Read one line at a time
- Result Two records
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.
#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;
}
[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
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.
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.