Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resume input stream after stopped by EOF in C++?

Tags:

c++

io

I want to write a program so that it takes two sets of integer input from terminal and computes two sums. My intention is to separate the two sets of input by EOF (pressing Ctrl+D). Here is my code:

#include <iostream>
using namespace std;

int main(){
    int i,sum=0;
    while((cin>>i).good())
        sum+=i;
    cout<<"Sum 1 is "<<sum<<endl;
    cin.clear();
    sum=0;
    while((cin>>i).good())
        sum+=i;
    cout<<"Sum 2 is "<<sum<<endl;
    return EXIT_SUCCESS;
}

The compiled program worked fine for the first set of integer inputs. But as soon as I pressed Ctrl+D, the first sum was computed and printed and, without taking any further input, printed the second sum as 0. So basically the second while loop failed at the very beginning, even though cin.iostate had been set to good before it. So why did this happen? How should I change the program so that the second while loop would proceed as intended?

like image 496
God_of_Thunder Avatar asked Jan 12 '23 14:01

God_of_Thunder


1 Answers

When you use Ctrl-D while the tty is in canonical mode it closed the system level pipe. Whatever you do to std::cin won't restore the stream into a good state. If you insist in using Ctrl-D to signal the end of the sequence (which is an unusual interface and probably best avoided), you'll need to clear the ICANON flag using tcgetattr() and tcsetattr() for the standard input stream (file descriptor 0). You will need to deal with any control characters.

It is probably easier to read up to the first failure, clear() the state and either ignore() the offending character(s) or check that they have a specific value.

like image 140
Dietmar Kühl Avatar answered Jan 22 '23 13:01

Dietmar Kühl