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.
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?
I've been working on a personal dictionary application which can help you remembering words you learnt. It is operated via the CLI (just don't question this, it's kinda just a test and I got a weird passion for CLI apps). So, of course I am using ostreams for writing information on the CLI. I am used to write operator<< overloads (for ostreams) for every class so that I can build up a multi-level output system (basically every object can "speak" for itself).
In order to persist a dictionary object, I wanted to use ofstream and write a file with it. Naturally, I wrote operator<< overloads also for ofstream and in the same "layered" structure.
As a result, I have now two operator<< overloads in every class, like in "Dictionary":
ostream& operator<<(ostream&, const Dictionary&);
ofstream& operator<<(ofstream&, const Dictionary&);
(this is just the declaration in the header file)
Notice that it is very important that these both overloads do different things. I don't want to have some weird persistence-oriented special-format text on the CLI and also not user-friendly plain text in my file.
The problem is that, because of the inheritance structure of ostream and ofstream, ofstream is sometimes implicitely converted to ostream. And when this happens in the middle of my stack full of file output operations, the program suddenly jumps into the wrong overload and prints plain text in the file.
My question is simply: Is there a way to avoid or revert these unwanted implicit conversions in order to let my program jump into the right overloads? Or is there any other good way to fix this problem?
EDIT 1:
Someone pointed out in the comments that this is not an implicit converison. ofstream is sometimes "seen" as its base class ostream. The problem is that at some point the object "forgets" that it is an ofstream and loses all file-related information. From there on it is only an ostream and that's what I meant with the "conversion".
EDIT 2:
The exact point in the program where the "unwanted conversion" happens can be found here:
ofstream& operator<<(ofstream& of, const Section& s) {
return s.print_ofstream(of);
}
So this operator overoad calls "print_ofstream":
ofstream& Section::print_ofstream(ofstream& of) const {
of << "sec" << Util::ID_TO_STRING(section_id) << ":\n";
for (pair<Wordlist, Wordlist> pwl : translations) {
of << '{' << pwl.first << '=' << pwl.second << "}\n";
}
of << "#\n";
return of;
}
Note that "pwl" is a pair of two Wordlists, therefore pwl.first / pwl.second is a Wordlist. So, normally the line of << '{' << pwl.first << '=' << pwl.second << "}\n"; should call the ofstream operator<< overload in Wordlist. But it doesn't. Instead, the other overload method is called:
ostream& operator<<(ostream& o, const Wordlist& wl) {
return wl.print_ostream(o);
}
You have overloaded only the specific operator<< needed for streaming Dictionary, Section, Wordlist, etc objects to a std::ofstream, but std::ofstream inherits MANY other operator<<s from std::ostream, and those operators all take ostream& as input and return ostream& as output. So, for example, of << "sec" will return ostream& even though of is a std::ofstream, and then that ostream& is used for subsequent << calls until ; is reached. Those are the "implicit conversions" you are experiencing.
The real question is, WHY do you want operator<< to output different data depending on the type of std::ostream being written to? That goes against C++'s streaming model. If you really want that, you would have to change print_ofstream(ofstream&) to print_ostream(ostream&) and then dynamically detect the actual std::ostream derived type using dynamic_cast. Same with Wordlist, and any other classes that need it.
A simpler and safer option would be to just store a flag inside of your classes to control how their data should be output, regardless of the type of std::ostream being used. Then you can set that flag as needed. Maybe even define some helper I/O manipulators to set those flags while making << calls.
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").
I am still confused about the difference between ostream& write ( const char* s , streamsize n ) in c++ and cout in c++
The first function writes the block of data pointed by s, with a size of n characters, into the output buffer. The characters are written sequentially until n have been written.
whereas cout is an object of class ostream that represents the standard output stream. It corresponds to the cstdio stream stdout.
Can anyone clearly bring out the differences between the two functions.
ostream& write ( const char* s , streamsize n );
Is an Unformatted output function and what is written is not necessarily a c-string, therefore any null-character found in the array s is copied to the destination and does not end the writing process.
cout is an object of class ostream that represents the standard output stream.
It can write characters either as formatted data using for example the insertion operator ostream::operator<< or as Unformatted data using the write member function.
You are asking what is the difference between a class member function and an instance of the class? cout is an ostream and has a write() method.
As to the difference between cout << "Some string" and cout.write("Some string", 11): It does the same, << might be a tiny bit slower since write() can be optimized as it knows the length of the string in advance. On the other hand, << looks nice and can be used with many types, such as numbers. You can write cout << 5;, but not cout.write(5).
cout is not a function. Like you said, it is an object of class ostream. And as an object of that class, it possesses the write function, which can be called like this:
cout.write(source,size);
"In binary files, to input and output data with the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...).
File streams include two member functions specifically designed to input and output binary data sequentially: write and read. The first one (write) is a member function of ostream inherited by ofstream. And read is a member function of istream that is inherited by ifstream. Objects of class fstream have both members. Their prototypes are:
write ( memory_block, size );
read ( memory_block, size );
"
from: http://www.cplusplus.com/doc/tutorial/files/
There is no function ostream& write ( const char* s , streamsize n ). Perhaps you are referring to the member function ostream& ostream::write ( const char* s , streamsize n )?
The .write() function is called raw (or unformatted) output. It simply outputs a series of bytes into the stream.
The global variable cout is one instance of class ofstream and has the .write() method. However, cout is typically used for formatted output, such as:
string username = "Poulami";
cout << "Username: '" << username << "'." << endl;
Many different types have the ostream& operator<<(ostream& stream, const UserDefinedType& data), which can be overloaded to enrich ofstream's vocabulary.
Oh boy! A chance to smash up a question.
From your question I feel you are some Java or Python programmer and definitely not a begginner.
You dont understand that C++ is probably the only language that allows programmers to implement primitive built in operators as class members and as part of the general interface.
In Java you could never go
class Money
{
int operator + (int cash) { return this.cash + cash; }
void operator << () { System.out.println(cash); }
int cash;
}
public class Main_
{
public static void Main(String [] args)
{
Money cashOnHand;
System << cashOnHand;
}
}
But cpp allows this with great effect. class std::ostream implements the stream operators but also implements a regular write function which does raw binary operations.
I agreed with Alok Save!A litte before, I searched the problem and read the answer carefully.
Maybe in other word, cout is an object of ostream, but write is just a function provided. So cout have twe ways to used by coders: one is as a member function, another is used by operator(<<).
Could anyone explain me the declaration of the setw manipulator? I was completely blown off trying to understand it.! The declaration of the setw in iomanip is as follows
smanip setw(int)
now what is smanip? what happens when we give std::cout << setw(10) << "Hai" [ i want to know how the output is actually affected by setw, in other words the actions happening under the hood)
smanip is an implementation-defined type. The library can define or typedef it to anything it likes, as long as the job gets done.
In practice, it will be some kind of structure representing (a) the manipulation to be performed, and (b) the argument 10 to be used in this manipulation. It might also have a function to perform the manipulation, or it might not, depending how the implementation has defined operator<<(ostream &, smanip), or some similar overload to catch the necessary operand types. I haven't checked my implementation to find out.
As for how the output is affected: my_stream << setw(10) is defined to have the same effect on the stream as calling my_stream.width(10). So the operator<< overload will ensure that happens in some implementation-specific way. The operator overload for non-parameterized stream manipulators is defined specifically to call the manipulator, but with smanip there's a little more freedom for implementations.
setw(int) by itself doesn't modify anything. It simply returns a stream manipulator (smanip) that can be used to modify the stream's behaviour.
// setw example
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
cout << setw (10);
cout << 77 << endl;
return 0;
}