C++ buffered stream IO

后端 未结 3 2012
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-06 07:46

I understand that by default all stream IO supported by C++ is buffered.

This means that data to be output is put into a buffer till it is full and then sent to the

3条回答
  •  盖世英雄少女心
    2021-01-06 08:23

    Try the following code:

    int main()
    {
        for( int i =0 ; i < 10; i ++ )
        {
            cout << i << " ";
            cerr << i << " ";
        }
    }
    

    The buffered output is usually flushed with the destruction of the stream object, so the code above will print (not always, ofc, but it does for me with gcc 4.6.3)

    0 1 2 3..9
    0 1 2 3..9
    

    instead of

    0 0 1 1 2 2 3 3 .... 9 9 
    

    my output

    Because the unbuffered cerr is printed right away (first sequence) , and buffered cout is printed in the end of main().

提交回复
热议问题