cout.write meaning of sizeof

Hello!
Please, what is the meanign of "sizeof) in there?
p.s. I tried to write the smae program without that, but got a millions of errrors I could not understand.

Cansomone tell me clear why does it have to be written?
(I ask because it is obviously not connected with the array size or?)

Many thanks!!

1
2
3
4
5
6
7
8
9
10
11
  #include<iostream>  
using  namespace std;  
 int main(){   

char day[]= "Today it is saturday!!!"; 
cout.put('o').put('\n').put('p').put('b').put('\n').put('\n');   

cout.day(day, sizeof(day));    
return 0;    

}
Last edited on
Small mistake on line 8:

8
9
// cout.day(day, sizeof(day));
   cout.write(day, sizeof(day)); 
Hello!
Thanks, but what confused me is what the size of the array has with the stuff???

I expected sth like writting out its size, it did nto happen, but without it I am getting millions of errors!

If somone has a practialy usefull explanation, I would be gratefull!
cout is an object of type ostream:

http://www.cplusplus.com/reference/iostream/cout/

If you look at the documentation for ostream::write(), you'll see that it takes as its second argument the number of bytes to insert. sizeof(day) is providing that number of bytes:

http://www.cplusplus.com/reference/ostream/ostream/
Last edited on
Thanks, but what confused me is what the size of the array has with the stuff???

Arrays, as inherited from the C language, don't know their own size.
They also decay to pointers. This means that every time you use an array's name, it becomes a pointer to the array's first element.

The two things above combined make it necessary that you pass the array's size together with the array, otherwise the function won't know where the array stops in memory.

An exception is char arrays (more specifically C strings). The trick with those is that they're NUL-terminated. The last element is NUL aka '\0', so a function knows that it can keep reading elements until it reaches that NUL.

That's why you can do std::cout << "Hello!"; without passing the size of "Hello".

On the other hand, std::ostream::write() is used for unformatted output, so the char array you're feeding it need not be a C string, but instead non-text binary data. Which is why you need to pass the size, because it doesn't stop at some 0 value.
Last edited on
Thanks! I think I got it!!!
Topic archived. No new replies allowed.