Question is in the title really; I\'m sure there is something logical, but for now I\'m stumped!
Insertion operator >>
and <<
are used with Input Stream and Output Stream respectively because Input stream
means flow of data into your program and Output stream means flow of data out of your program.
As these insertion operators look like Directional operator (Showing direction of flow of data),
so >>
is chosen for Input stream and <<
for the Output stream.
Have a look at the part of code...
int Num1;
cin >> Num1;
here if you observe carefully >>
is showing flow of data to variable (declared in program)
that means the flow of data to the program , which is a job of Input stream (here cin
).
similarly goes with cout
,
int Num2 = 5;
cout << Num2;
Here <<
showing the flow of data out of the program (as Num2
is part of the program), which is the job of Output stream.
I hope all this make sense to you.
Because they had more or less a reasonable precedence and looked good. In C++ you cannot create new operators or change their precedence or grouping rules, you can only overload existing ones and changing what they actually do.
The choice of <<
and >>
has some unfortunate side effect because it's somehow pushing the idea that the output will be done respecting the order. While this is true for the actual output thanks to a clever chaining trick it's however false for the computations involved and this is very often surprising.
To be more specific writing
std::cout << foo() << bar() << std::eol;
does NOT imply that foo
will be called before bar
.
With C++17 the sequence problem has been "fixed". Now the order of evaluation is specified to be left-to-right for <<
and >>
operators. There are still places in C++ where the order of evaluation is unspecified (or even non-existing meaning that evaluation can be interleaved) but a few common cases now behave in a predictable and portable way see this answer .
Maybe because it looks similar to the Unix append operation, as you are essentially appending to an input/output stream?
E.g.
echo "foo" >> bar
sendmail -f test@domain.com << myemail.txt
(Stole input example from Zac Howland)
Mostly because of their associativity. The insertion and extraction operators associate from left to right, so
std::cout << "Hello" << ' ' << 4 << 2;
evaluates as you'd expect: first with "Hello"
, then with ' '
and finally with 4
and 2
. Granted, the addition operator, operator+
also associates from left to right. But that operator and others with left-to-right associativity already have a different meaning.
So you remember that if you think cin
as a keyboard and cout
as a monitor, what you type goes into the variable
cin>>var;
Or the contents of your variable goes towards the screen
cout<<var;
Bjarne chose them for practical precedence, associativity and mnemonic value.
The precedence isn't perfect, e.g. the boolean and bit-level operators are troublesome.
But it's fairly OK.