zoukankan      html  css  js  c++  java
  • c++ 流的clear 与sync

    先看函数原型:

    ios::clear 

    void clear ( iostate state = goodbit );
    Set error state flags

    Sets a new value for the error control state.

    All the bits in the control state are replaced by the new ones; The value existing before the call has no effect.

    If the function is called with goodbit as argument (which is the default value) all error flags are cleared.

    The current state can be obtained with member function rdstatehttp://www.cplusplus.com/reference/iostream/ios/clear/

    istream::sync

    int sync ( );
    Synchronize input buffer with source of characters

    Synchronizes the buffer associated with the stream to its controlled input sequence. This effectively means that the unread characters in the buffer are discarded.
    The function only has meaning for buffered streams, in which case it effectively calls the pubsync member of thestreambuf object (rdbuf()->pubsync()) associated to the input sequence.

         简而言之,clear是使流恢复正确的状态即清除流的错误状态,而sync则是来清除缓存区的数据流的。 如果流的状态没有恢复到正确的状态那么即使清除了数据流也无法输入。 所以两个要联合起来使用。

    #include<iostream>
    #include<stdexcept>
    using  namespace std;
    
    int main()
    {
        int val;
        while(1)
        {
            cin>>val;
             
                if(cin.bad())
                    throw runtime_error("io stream corrupted");
         
            if(cin.fail())
            
            {
                cerr<<"bad data, try again" << endl;
                cin.clear(); //去掉后会输入一个错的后会一直输出bad data ,try again
                cin.sync();  //去掉后会输入一个错的后会一直输出bad data ,try again ,两个顺序不能颠倒
                continue;
            }
            if(cin.good())
                cout<<val<<endl;
        }
        return 0;
    }

    清空输入缓冲区:
    fflush(stdin);
    std::cin.sync();
    cin.ignore(1000, '\n')   //忽略指定大小的内容,到制定字符结束忽略;常用来清空缓冲区

    清空输出缓冲区:
    fflush(stdout);
    std::cout.flush(); 
    endl也有清空输出缓冲区的功能.

  • 相关阅读:
    1104
    HDU 1575
    hdu 1142(DFS+dijkstra)
    hdu 1015(DFS)
    hdu 1342(DFS)
    hdu 1181(DFS)变 形 课
    hdu 1312(DFS)
    hdu 5976 Detachment
    hdu 5795
    UVa 11729
  • 原文地址:https://www.cnblogs.com/youxin/p/2452153.html
Copyright © 2011-2022 走看看