Resume reading from iostream::cin after Ctrl+Z (EO

2019-01-28 07:22发布

问题:

Why does the outer loop in the following program terminate when we provide ctrl+z for the inner loop only?

#include<iostream>
int main()
{
    string s1,s2;

    while(cin >> s1)
    {
        cout<<"In loop1\n";
        while(cin>>s2)
            cout<<"In loop 2\n";
        cin.ignore();
    }
}

回答1:

Hitting Ctrl+z (on Windows) closes the standard input stream. Once it's closed, it stays closed. It doesn't magically reopen once the inner loop is finished. There's just no reason why it would.



回答2:

Ctrl-Z puts cin into an error state so cin.ignore does nowt. try cin.Clear() instead.



标签: c++ stdin