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?
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.
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.
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.
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").
Related
Question is in the title really; I'm sure there is something logical, but for now I'm stumped!
According to §8.3.1 of The Design and Evolution of C++:
The idea of providing an output operator rather than a named output function was suggested by Doug McIlroy by analogy with the I/O redirection operators in the UNIX shell (>, >>, |, etc.)
[...]
Several operators were considered for input and output operations:
the assignment operator was a candidate for both input and output, but it binds the wrong way. That is cout=a=b would be interpreted as cout=(a=b), and most people seemed to prefer the input operator to be different from the output operator.
The operators < and > were tried, but the meanings "less than" and "greater than" were so firmly implanted in people's minds that the new I/O statements were for all practical purposes unreadable (this does not appear to be the case for << and >>). Apart from that, '<' is just above ',' on most keyboards, and people were writing expressions like this:
cout < x , y, z;
It is not easy to give good error messages for this.
Maybe because it looks similar to the Unix append operation, as you are essentially appending to an input/output stream?
E.g.
Output
echo "foo" >> bar
Input
sendmail -f test#domain.com << myemail.txt
(Stole input example from Zac Howland)
From "The C++ Programming language". Stroustrup's(language authors) words:
Overloading the operator << to mean ‘‘put to’’ gives a better notation and lets the programmer output a sequence of objects in a single statement.
But why <<? It is not possible to invent a new lexical token . The assignment operator was a candidate for both input and output, but most people seemed to prefer to use different operators for input and output. Furthermore, = binds the wrong way; that is, cout=a=b means cout=(a=b) rather than (cout=a)=b . I tried the operators < and >, but the mean ‘‘less than’’ and ‘‘greater than’’ were so firmly implanted in people’s minds that the new I/O statements were for all practical purposes unreadable.
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.
EDIT
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 .
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;
>> and << are just operators and you can implement your own >> and << for your classes.
I suppose "somebody" selected them because: a) they are similar to shell file operations and b) to reuse existing operators because there are no need to create new ones
They are not bitwise operators, They are called insertion and extraction operators in this context.
http://www.cplusplus.com/doc/tutorial/basic_io/
These are used only for visual interpretation. If you study developing own stream and operator overloading, then you can see that you can even use + for input and - for output :)
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.
This answer is unsatisfying but correct: they aren't bitwise operators.
The meaning of the operator is determined by the data-type that appears on its left. In the case of cin and cout (and other stream types) << and >> operators move values to and from streams. In the case that the left operand is an integer, the operation is the bitwise operation that you already know from C.
The meaning of the operator is not fixed, although its precedence is.
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.
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.
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen
The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted the constant string Output sentence, the numerical constant 120 and variable x into the standard output stream cout.
The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. For example:
int age;
cin >> age;
I assume that you are aware that C++ allows for operator overloading. In general, you overload operators only if the semantics are completely transferable (e.g. overloading the addition for a vector class to add two vectors together). I think your question refers to why one would use bitshift operators, overload them for the iostream, and give them a completely different meaning than their original purpose. The reason it can be done is because bitshift operations are so far removed from what iostreams do that no one could be confused into thinking that << or >> is doing a bitshift on an iostream. And the reason why they are convenient to use also is that their ordering is to evaluate the operand on the left first, then the one on the right, and do the operation. This fits to what you would want to happen when you are using the operators to append or extract stuff from an iostream.
But, to the original question, why? I don't really know, it just seems to me like the << and >> are pretty easily understood as taking information from one entity and putting it in the other. Why does the reason need to be more complicated than that? It looks sensible to use those because their meaning is obvious.. what better could you ask of an operator?
Im working with the book SFML Game Development by Examples and I dont really get what this sentence does. I've never seen something like this
void Anim_Directional::ReadIn(std::stringstream& l_stream){
l_stream >> m_frameStart >> m_frameEnd >> m_frameRow
>> m_frameTime >> m_frameActionStart >> m_frameActionEnd;
}
In C++ they got the "bright" idea of overloading the rightshift and leftshift operators with streams to represent serialization/deserialization.
stream >> var
means "read var from stream".
Symmetrically
stream << var
mean "put var into stream"
The operation of "streaming" in or out also returns the stream, so you can chain operations like:
stream >> var1 >> var2;
Note that the "streaming" was chosen just because of the look and because the priority was considered reasonable, but it's still just an overloaded operator and implies for example no strict sequence of evaluation. For example in:
stream << f() << g();
may be function g is called (somewhat surprisingly) before function f.
NOTE: the sequencing problem was handled by hammering this special case in last C++ standard (C++17). While it doesn't hold in general it's guaranteed for shift operators (presumably for this specific reason). So in f()+g() may be f is called later than g, but in f()<<g() this cannot happen.
C++ allows you to overload >> and << operators. std::stringstream is a derivative of std::istream and it inherits the >> operator overloads of std::istream.
The std::istream has a bunch of overloads for many common types. You can find a list of them here.
A typical std::istream >> operator overload looks as follows:
std::istream& operator>>(std::istream& stream, YourType& var) {
/*
** code here to parse and read a 'YourType' into 'var'
*/
/* var is set */
return stream; /* return the same stream to allow chaining */
}
When you do some_stream >> YourType_object, the matching >> operator overload is invoked. In the aforementioned case, our operator overload is invoked with stream parameter taking some_stream and var taking YourType_object.
The >> overloads (and << overloads too) intelligently return the stream which they operated; thereby, allowing a series of >> operators to be chained.
Suppose you want to convert an integer into string this is the method in c++
int c1=999;
stringstream ss;
ss<<c1;
string str=ss.str();
How is it converting into string in c++? What does the stringstream contains and in the 3rd line of the above program
in that statement i.e I mean what does the left shift operator (as we know that the symbol '<<' is used for left shifting) is doing here to converting into string
To convert an int to string (very basically), you have to go through all digits, translate it to a regular char, and put it in the string :
int toConvert = 999;
string res = "";
while (toConvert)
{
int lastDigit = toConvert % 10; //retrieve last digit
char c = lastDigit + '0'; //translate it to the char corresponding
string reverse(c); //We have to add it in front of the string, or otherwise
reverse.append (res); // the digits will be reversed.
res = reverse;
toConvert /= 10;
}
This is a very basic way to translate int to string, and I'm sure it's done way better in the operator "<<", but you get the idea.
The left shift here is overload by append function, think of it as
ss.append(c1) where the append can have multiple functions
append(int i)
append(string s)
append(byte b)
etc
each function do the actual translation to the right string and appending it...
There's no left shift operator in your code. In C, << was left shift. In C++, it's the stream insertion operator (with support for left shift as well, for reasons of C compatibility).
You are allowed to overload various operators in C++, including bitwise left shift <<. Conceptually you can override it do to anything; the only restriction being that the number of operands can't be changed.
The streaming classes in the C++ IO stream libraries exploit this. It's syntatically cute to use << to write the argument to the stream in some way, as clearly, bitwise shifting a stream has no meaning so the operator may as well be used to do something else. That is what ss<<c1; is doing. It's not doing anything like a bitwise shift.
There is a school of thought that says that operator overloading is confusing (perhaps this is why this question has been asked). That's why operator overloading didn't make it into Java.
<< in this situation isn't exactly the Left Shift Operator.
Its a Stream Operator.
It appends (inserts) the characters in to your string stream.
I don't quite understand what this means...I'm just learning C++ from my very very very basic Python experience...and so this may be a very stupid question. My question is...say you have your classic "Hello World" program and you have the line:
cout<<"Hello World!"<<endl;
what does the << mean...because I was just looking at using input in C and saw that you'd do something like:
int i;
cin>>i;
and I noticed that it has >> instead of << and I've read that those are bitwise shifts...and I don't exactly understand what those are...but I think it might be different here...Help...Thanks in advance
In Python, you can implement __lshift__ and __rshift__ to do whatever you want. In C++, it is the same - while the classic meaning is bitwise shift right and bitwise shift left, you can make it do whatever you want.
This is probably one of the most blatant violations of "sensible" operator overloading in C++, but that is just how std::ostream and std::istream work. For all of the C++ lovers out there (myself included), I apologize for this strange choice of operators. Just think of it as the direction that the data flows in (cout << foo puts a foo in cout, cin >> foo puts cin in foo), smile and be happy. From a newcomer, it really doesn't make sense, but drink the C++ Kool Aid and you'll be OH YEAH about it. Trust me.
Operators can have different meanings when applied to different types, and C++ allows the developer to overload operators to do just that. It's a powerful technique that should be used cautiously, since it's really easy to make programs unreadable if you overload unjudiciously.
Therefore >> and << are bit shift operators when the left side is an integer, but input and output operators when the left side is an I/O stream or similar. Read them as arrows pointing which direction the data flows.
Originally, it did mean bitshift. And you can still use it as a bitshift for an int (or other basic type).
Classes let you redefine operators. This allows you to create iterators, for which ++ actually does what you want (iterates to the next element), by modifying an internal member appropriately.
<< and >> are also operators, which can be redefined for classes, and this allows them to be used as "stream insertion/extraction operators".
The ostream class actually defines ostream& operator<< (Type); and the istream class defines istream& operator>> (Type&);
You can see more details about i/ostream here: http://www.cplusplus.com/reference/iostream/
Full details of ostream's operator<< and of istream's operator>>.
You can even write your own such operators to be able to do cout << myclass;:
class MyClass{ ... };
ostream& operator<< (ostream& os, const MyClass& myclass) {
// code to insert it, usually something like:
return os << myClass.a << ' ' << myClass.b;
}
// and now you can do this:
MyClass m;
std::cout << m;
The << and >> operators are bitshift operators, but, for input/output streams, they are overloaded (=>their meaning is redefined) so that they are used to insert/extract stuff into the streams.
I think they were used because they look intuitive (they indicate the direction of the stream of data) and because they are almost never used for other purposes.
Instead of saying
print "Hello" + "world" #I know, you wouldn't actually do it like this.
where "print" is the command and "hello world" is your text,
c++ works as
cout << "Hello" << "World"; // or like this. But...
int i = 42;
cout << "The answer is: " << i; //you may want to do this
c++ uses "cout" as the command and "<<" as a joiner, or, more technically, an operator used on the out stream.
cin works similarly where the >> is just an operator that works on the in stream.
i have an overloaded operator << trying to make it work like this
mystream<<hex<<10;
i have overloaded method
mytream& operator<<(ios_base& (*m) ios_base&)
This gets called whenever hex is encountered cause the parameter passed in the method is a function pointer of type same as hex or like some other output manipulators like dec, oct.
i have two problems
1) how do i retrieve the parameter the hex would be operating on, in this example 10
2) how do i know that the << operator is being called for hex and not other manipulator function like oct and dec
Thanks
1) hex is not operating on the parameter 10. << operators associate left-to-right, which means your code is the same as:
(mystream<<hex)<<10;
So your overload has to return an object which, when 10 is shifted into it, prints in hex (or if not prints, writes data somewhere). As everyone says, this is done by saving flags in the stream object itself, then returning *this. The reason flags are used is precisely because the "10" is not available yet, since the second << has not been evaluated yet. The first << operator call cannot print anything - it just has to get ready for when the second one is called.
2) hex is a function. It can be compared with other functions:
ostream &operator<<(ostream &s, ios_base& (*m)(ios_base &)) {
if (m == hex) {
} else if (m == oct) {
} else if (m == dec) {
}
}
Except you don't normally want to do that, you want the default behaviour, which is something like:
ostream &operator<<(ostream &s, ios_base& (*m)(ios_base &)) {
return m(s);
}
(I may be wrong on that, I've never looked at the implementation, but the general idea is that the operator calls the manipulator function, and the manipulator (the clue's in the name) manipulates the stream).
std::hex sets the std::ios::hex format flag on its parameter. Then in your operator<<(int) override, if you have one, check the format flags by calling flags().
3) Manipulators which take paramers are functions too, but their return types are unspecified, meaning it's up to the implementation. Looking at my gcc iomanip header, setw returns _Setw, setprecision returns _Setprecision, and so on. The Apache library does it differently, more like the no-args manipulators. The only thing you can portably do with parameterized manipulators is apply them to an iostream with operator<<, they have no defined member functions or operators of their own.
So just like hex, to handle setw you should inherit from std::ios_base, rely on the operator<< implementation provided by your library, then when you come to format your data, examine your own width, precision, etc, using the width(), precision(), etc, functions on ios_base.
That said, if for some bizarre reason you needed to intercept the standard operator<< for these manipulators, you could probably bodge something together, along these lines:
template <typename SManip>
mystream &operator<<(mystream &s, SManip m) {
stringstream ss;
// set the state of ss to match that of s
ss.width(s.width());
ss.precision(s.precision());
// etc
ss << m;
// set the state of s to match that of ss
s.width(ss.width());
s.precision(ss.precision());
// etc
return s;
}
I do consider this a bodge, though. You're not really supposed to interfere with stream manipulators, just let your base class do the work and look up the results.
When operator<< gets called with hex or oct or dec, set a flag in your mystream object. When operator<< is called with a number, check to see if any of these flags are set. If so, convert the number to hex/octal/decimal and display it.
In answer to your second question, the parameter m is a pointer to the manipulator function. You can check that it's not null, then call that function, passing *this. hex() is as simple as setting a flag in the passed stream object, as Zifre suggested. Then when processing the integer, check if the flag in the stream object is set, and output accordingly.
This is how the standard library implements its manipulator functions.
In your example, hex operates on (changes the state of) the stream, not the following parameters. hex has no notion of, or any relation to other << calls.
Looking at how other io manipulators are implemented would go a long way to clearing things up.
You should be manipulating ios_base::flags
http://www.cplusplus.com/reference/iostream/ios_base/flags/
which is what the standard hex does.