Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading