std::getline() does not accept empty input

  c++

I want to be able to accept both a non-empty and empty string (as in just an endline without spaces) as input. The below code works as long as there is no empty input – which will result in the code simply waiting for an input instead of continuing. The cin.ignore() is required for it to not skip the first input (likely because I have other inputs using cin previously). Am I wrong to assume that getline() accepts empty strings?

std::cin.ignore(1,'n');
std::vector<std::string> words(n, "");
for (int i = 0; i != n; ++i) {
  std::getline(std::cin, words[i]);
}

I have tried using cin.clear() and cin.ignore() within the loop, but it ended up dropping inputs. What should I do to fix this?

Minimum reproducible example:

#include <iostream>
#include <vector>

int main() {
  int n = 0;

  std::cin >> n; 
  std::cin.ignore(1,'n');

  std::vector<std::string> words(n, "");

  for (int i = 0; i != n; ++i)
    std::getline(std::cin, words[i]);

  for (int i = 0; i != n; ++i)
    std::cout << words[i] << std::endl;
  
  return 0;
}

Input

5
One
Two
Three

Four
Five

Output

One
Two
Three
Four
Five

Expected output

One
Two
Three

Four

Source: Windows Questions C++

LEAVE A COMMENT