Comp Sci Difference between cout and cout.write in C++

  • Thread starter Thread starter Ilikecereal
  • Start date Start date
  • Tags Tags
    C++ Difference
Click For Summary
cout.write is a method specifically designed for writing a specified number of characters from a string, while cout uses the overloaded << operator to stream various data types. The primary distinction lies in cout's ability to handle different data types seamlessly, whereas cout.write is limited to character arrays or strings. In the provided code example, both cout and cout.write can output the same string, but cout.write explicitly controls the number of characters written. This makes cout.write useful for scenarios where precise output length is necessary. Understanding these differences helps in choosing the appropriate method for output in C++.
Ilikecereal
Messages
17
Reaction score
1
What's the purpose of cout.write. Isn't it pretty much the same thing as cout?

For eg, the following code would work the same with cout and cout.write

int main( )
{ char string[80] ;
cout<<"Enter string\n" ;
cin.getline(string, 80) ;
int x1 = strlen(string) ;
for(int i = 0 ; string != '\0' ; i++)
if(string == ' ')
string = '-' ;
cout<<"The changed string is\n" ;
cout.write(string, x1) ;
return 0 ;
}
 
Physics news on Phys.org
cout.write() is the public method to actually write a string.

cout is used in an overloaded version of the << operator.
In particular this allows you to stream any type into cout, which is not something cout.write supports.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 24 ·
Replies
24
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 7 ·
Replies
7
Views
2K
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 8 ·
Replies
8
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 14 ·
Replies
14
Views
5K