c++ 流的clear 与sync

先看函数原型:

ios::clear

void clear ( iostate state = goodbit );

Set error state flags
Sets a new value for theerror control state.



All the bits in thecontrol stateare replaced by the new ones; The value existing before the call has no effect.



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



The current state can be obtained with member functionrdstate. http://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 thepubsyncmember of thestreambufobject (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也有清空输出缓冲区的功能.

原文链接: https://www.cnblogs.com/youxin/archive/2012/04/16/2452153.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/47582

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午11:35
下一篇 2023年2月8日 下午11:36

相关推荐