C++ C++;:进入EOF后,cin流的状态能否恢复

C++ C++;:进入EOF后,cin流的状态能否恢复,c++,C++,以下是我的测试代码: #include<iostream> using namespace std; istream& func(istream &); int main() { if(func(cin)) cout<<"good"<<endl; return 0; } istream& func(istream &is) { int num; is.clear(); auto

以下是我的测试代码:

#include<iostream>
using namespace std;
istream& func(istream &);
int main()
{
   if(func(cin))
       cout<<"good"<<endl;
   return 0;
}
istream& func(istream &is)
{
    int num;
    is.clear();
    auto old_state = is.rdstate();
    while(is>>num)
        cout<<num<<endl;
    is.setstate(old_state);
    return is;
}
#包括
使用名称空间std;
istream&func(istream&);
int main()
{
if(func(cin))
cout这是因为没有真正清除旧标志(请阅读链接参考以了解原因)


如果要完全重置标志,则需要使用该函数。但我并不推荐使用该函数,因为它会给您错误的流状态。相反,您应该显式检查状态。

无效输入后可以恢复状态:根据预期类型解析输入失败只会设置
std::ios_base::failbit
可以
清除()
编辑。由于未删除导致问题的字符,您可能需要删除它(例如,使用
忽略()
)或以不同方式排列数据

虽然EOF也只是一个标志(
std::ios_base::eofbit
),但一般来说,清除它不会从到达流结束时恢复。特定流可能有方法进行读取,但在流结束指示器(例如Ctrl-D或Ctrl-Z)后,控制台可能会断开连接。根据系统的不同,可能会创建到控制台的新连接,例如,打开文件流至
/dev/tty


如果确实要使用控制字符来指示特殊处理,则需要禁用默认处理并在程序中管理它们。在UNIX系统上,您可以使用
tcgetattr()
tcsetattr()将流设置为非规范模式
。完成此操作后,所有输入的字符都会被看到,并且可以进行相应的处理,可能是在自定义流缓冲区中。我不知道如何在其他系统上执行类似操作。

您需要忽略eror,然后将其清除。例如,您只需将while循环更改为类似以下内容:

    while(true)
    {
        if(is>>num)
            cout<<num<<endl; //if cin is numeric
        else // we have an error
        {
            is.ignore(); // ignore the last error (else your program will run crazy)
            is.clear(); // clear the state
            break; // terminate console reading
        }
    }
while(true)
{
如果(是>>num)

coutYour的想法很好。但是“在流结束指示器(例如Ctrl-D或Ctrl-Z)后,控制台可能会断开连接。”正如Dietmar Kühl指出的。输入“EOF”,程序结束。这可能与系统相关。哦,我完全忽略了问题的EOF部分。那么,便携式方法不是使用“信号”这样的信号处理程序吗(SIGINT,mysignalhandlingfunction);“还有“clear()”来清除“cin”的状态吗?
    while(true)
    {
        if(is>>num)
            cout<<num<<endl; //if cin is numeric
        else // we have an error
        {
            is.ignore(); // ignore the last error (else your program will run crazy)
            is.clear(); // clear the state
            break; // terminate console reading
        }
    }