Home > Mobile >  How do I read from cin until it is empty?
How do I read from cin until it is empty?

Time:09-23

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);
}

CodePudding user response:

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.

CodePudding user response:

If you take input from a file and pass it to your c compiled program

cat input_file.txt | cpp_binary_executable

then the cin in a while loop will read till the end of file

    string temp;
    while (cin >> temp) //read till the end of file
    {
        cout << temp << endl;
    }

CodePudding user response:

The idiomatic way would be:

while (getline(cin, str1) && getline(cin, str2)) {
    // ...
}

Or even:

while (getline(getline(cin, str1), str2)) {
    // ...
}
  •  Tags:  
  • c
  • Related