I know Java and now want to learn C++. I can't understand what are cout (character output stream) and cin (character input). Are these global variables? Then why
"My message">>cout;
doesn't work? But
cout<<"My message";
works.
The cout object in C++ is an object of class ostream. It is defined in iostream header file. It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout.
The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.
Hence cin means "character input". The cin object is used along with the extraction operator >> in order to receive a stream of characters.
std::cout and std::cin are indeed global variables. Your code doesn't compile because that's not the way the language works. You have to put the stream on the left, and then the operator and then the variables you are streaming into/out of. (For output, you can use literals and expressions as well as variables.)
cout
is an instance of the class std::ostream
, and yes, it's a global variable. But operator>>(char *, ostream& os);
hasn't been declared by the relevant header, so "My message">>cout;
will give an error of something like "can't find an operator >> which takes arguments const char * and std::ostream" (and possibly a lot more errors because sometimes compilers get very confused by these sort of things).
cin
is the same thing, except std::istream
If you really want to mess with peoples heads, you could do:
template<typename T>
std::ostream& operator>>(T x, std::ostream& os)
{
os << x;
return os;
}
Of course, it won't work for "My Message " >> "Some other string" >> cout;
, which is probably one of the reasons it's not done that way.
Note that this is simply slight abuse of the operator overloading, where we have a custom type as the left-hand side, and standard or non-standard type on the right hand side. cout
is no different from some other variable of a custom type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With