Using getline after extraction

The Problem

When using the getline function to read in text all the way to the delimiter (default to the new line character), the text may be empty after the read if the delimiter is the first character in the string. It causes the problem that if you call this function after an extraction >> operation, you may potentially read in an empty string.

The Solution

  • Option 1: keep calling getline until you get a non-empty read

  • Option 2: clean up after inputs with leftovers such as extraction operations

  • A formal way: make a function to do the work

Code Example

 1// ==== Wrong ====
 2int input;
 3string line;
 4
 5cout << "Input an int: ";
 6cin >> input;  // leaves a new line character as the first char in the stream
 7cout << "Input a line of text (may contain spaces): ";
 8getline(cin, line);  // the line variable will be an empty string
 9
10// ==== Correct ====
11// option 1: protect the getline and replace the getline with:
12do {
13  getline(cin, line);
14} while (line.empty());
15
16// option 2: protect the extraction add after the last >> before getline
17// to clear the leftover
18cin.ignore();
19cin.ignore(numeric_limits<streamsize>::max(), '\n'); // a safer version
20
21// recommended: make a function
22string readline() {
23  string text;
24  // text is initially empty so a while loop works here
25  while (text.empty()) getline(cin, line);
26  return text;
27}
28// to call:
29line = readline();