spurra
spurra

Reputation: 1025

"<< / >>" Operators in C++

So since I can't find anything on Google due to them somehow not accepting the search term ">>", I decided to ask here.

First of, no I do not mean the bitwise shift operator. This is different. I've seen it occur in some code and it would make no sense if it was a shift operator.

cout << a; would be an example. I know it prints out a, but what is the definition of "<<"?

Or in my case, I have a code similar to this:

for(int index=0;index<n;index++)
    inputFile >> StringArray[index];

What does it mean?

Upvotes: 3

Views: 197

Answers (4)

ergysdo
ergysdo

Reputation: 1159

These are called bitwise operators, as you said.

However, in C++ you can overload these operators (in fact any operator) to do what you want them to. This is what is happening here. The << and >> are overloaded in the ostream and istream objects, to print to and read from a stream, respectively.

In fact you could overload any operator to do whatever you want on an object. An example can be found here.

Cheers.

PS: The concept around these operators is easily visualized. When you write:

cout << "Hello world";

with a little bit of imagination, you could say that you "put" the string on the right to the cout stream on the left (thus the left directed "arrows"). Same, when you write:

std::string str;
cin >> str;

you could imagine that you extract a string from the cin stream on the left and "put" it on the str variable on the right (thus the right directed "arrows").

Upvotes: 1

Roy Dictus
Roy Dictus

Reputation: 33139

It's about writing to or reading from streams.

Check this out for a practical example: http://www.cplusplus.com/doc/tutorial/files and http://www.umich.edu/~eecs381/handouts/filestreams.pdf‎.

Upvotes: 1

Praveen
Praveen

Reputation: 2419

They are bitwise shifting overloaded operators, usually called 'stream operators' I don't know it in detail but as you said,

cout<<a;

outputs the value of a, that is it puts the value of a into the output stream which get displayed on the screen.

And in the case of

inputfile>>variable; 

You are reading the data from the file into the variable.

Upvotes: 1

yan
yan

Reputation: 20982

The bitshift operator is frequently overloaded to mean reading values from and writing to streams.

Edit: In slightly more detail, C++ lets you overload, or change the meaning of, almost any operator. The << and >> operators were chosen to be overloaded for writing/reading to a source or sink of data because they visually look like arrows or conduits. There is zero commonality with shifting bits except as to what operator is used.

Upvotes: 7

Related Questions