cin.clear() leave EOF in stream?

柔情痞子 提交于 2020-12-13 05:45:24

问题


I have a question about cin.clear(), my cpp code like this:

#include <iostream>

using namespace std;


int main(void)
{
        char c, d;
        cout << "Enter a char: " << endl;
        cin >> c;                            // here I will enter Ctrl + D (that is EOF under linux)
        cin.clear();
        cout << "Enter another char: " << endl;
        cin >> d;

        return 0;
}

I compiled and run this code under 2 systems: one system is Debian 7 with older version of software like g++ and library

 g++ --version
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

another system is Arch linux with newer version of software:

g++ --version
g++ (GCC) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

When I run this program , I enter Ctrl + D (EOF) when it ask me to "Enter a char: ". The problem is that When I run it under Debian 7, I can Enter a char when the program asks me to "Enter another char: ", but I will not be able to do the same under newer system, the program just finished.

It seems that cin.clear() will clear eof bit and flush EOF in the stream under older system, with newer system cin.clear() will clear eof bit, but leave EOF in the stream untouched.

Is this caused by some new cpp standards? And why cin.clear() behave differenly under 2 systems?


回答1:


I have the same issue in Ubuntu 20.

I find the solution from How to restart stdin after Ctrl+D?

Terminal doesn't really close stdin stream. The stream just return "nothing" to indicate EOF or other troubles.

To clear EOF, calling clearerr(stdin) in your program may solve the problem.

#include <iostream>

using namespace std;

int main(void)
{
    char c, d;
    cout << "Enter a char: " << endl;
    cin >> c;
    clearerr(stdin);
    cout << "\nEnter another char: " << endl;
    cin >> d;

    cout << "\n\nc = '" << c << "' and d = '" << d << "'\n\n";

    return 0;
}

My g++ version is 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
My OS is ubuntu 20 x64
My terminal is gnome-terminal 3.36.1.1



来源:https://stackoverflow.com/questions/58732434/cin-clear-leave-eof-in-stream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!