Difference between operator<< and write function?

I wonder what is the difference between std::basic_ostream<CharT,Traits>::operator<< and std::basic_ostream<CharT,Traits>::write. What about performance?

#include <iostream>
#include <string>

int main()
{
    std::string tempMsg;
    tempMsg.reserve( 100 );
    tempMsg += "This is a string";

    std::cout.write( tempMsg.data( ), tempMsg.size( ) ).write( "\n", 1 );
    std::cout << tempMsg << '\n';
}

They both print the same string. But what are the advantages of each of them?

1 answer

  • answered 2021-12-05 10:08 Vlad from Moscow

    The function allows to specify the number of characters to be outputted for a character array.

    For example of you have declaration

    const char *s = "Hello World!";
    

    and want to output only the word "Hello" from the string literal then you can write

    std::cout.write( s, 5 );
    

    If you will write

    std::cout << s;
    

    then the whole string literal will be outputted.

    Thus using the function you can output any part of a character array as for example

    std::cout. write( s + 6, 2 ) << 'w' << s + 11 << '\n';
    

    As for the performance then there is no difference or the difference is insignificant. What is important is the functionality.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum