How do I read from cin until it is empty?

I am trying to read pairs of lines from a file passed in through the cin. I need to read until the file is empty. If one line of the pair is empty, I need to save that line as “”. If both lines are empty, then both need to be saved and processed as “”.

I am using the getline to read the lines in, with a while-loop that keeps going until both lines are empty. However, I need it to continue until the file is empty, as it is possible that 2 empty lines are followed by a number of filled lines.

This is how I have it at the moment:

getline(cin, str1); getline(cin, str2);
while (str1 == "" | str1 != "") {
  ....
  str1 = ""; str2 = "";
  getline(cin, str1); getline(cin, str2);
}

Answer

If the file contains two line feeds in a row this would not work. You can use cin.eof() to check when you’ve reached the end of the file. If it returns 1 then you’ve attempted to read beyond the end of the file.