• 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也有清空输出缓冲区的功能.

  • 相关阅读:
    Linux操作系统原理
    html标签简介(常用)
    Git常用命名
    Nuxt.js vue服务端渲染
    Sequelize 和 MySQL 对照Sequelize 和 MySQL 对照
    VScode 自定义用户代码块
    python对一个文本的解析
    API管理工具
    Flutter教程- Dart语言规范-知识点整理
    RESTful API
  • 原文地址:https://www.cnblogs.com/youxin/p/2452153.html
Copyright © 2020-2023  润新知