C++ i/o operator
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Jun 2, 2013, 6:28 AM EDT
1. << and >> are briefer to write than function names such as output and input respectively.
2. It's easy to use operators multiple times in the same line of code.
3. You can overload these operators to provide 'inserters' or 'extractors' for your own classes which work in an analogous way to the basic stream operations.
EDIT:
I've just checked Bjarne Stroustrup's book, The C++ Programming Language (3rd edition) and it says, in section 21.2 Output, that the use of functions would be repetitive.
"Overloading the operator << to mean 'put to' gives a better notation and lets the programmer output a sequence of objects in a single statement."
It also goes on to say:
"This style can be used as long as x is of a type for which operator << is defined and a user can trivially define operator << for a new type."
I can't find any explanation about the use of >> for input but, logically, if you use an operator for output you should do the same for input.
So it looks like my answer on this was not wide of the mark.
Sam HobbsRank #107 · 20.5K reputationPosted Jun 2, 2013, 9:46 PM EDT
std::wcout << L"Hello\n";
std::wcout.write(L"Hello again\n", 12);
They both work. Note that the "<<" and ">>" operators provide formatting, which can be a significant convenience, but if your requirements are more advanced than what the "<<" and ">>" operators can provide then you just need to learn more about how C++ works.