Input and output

Input and output in C++ are handled after including a Standard library called iostream.h into the code. It will provide you with a number of functions related to input or output, to be exemplified below:
#include <iostream.h>

int main() {
    double in_number;
    cout<<"What number ?"<<endl;
    cin>>in_number;
    cout <<"Number was "<<in_number <<endl;
}

We can read off the following operators:
  • cout is used to steer a line of output.
  • cin is used to steer the input (which has to be finished with "Enter").
  • << is used to separate different chunks of output. Explicit word strings have to go between "".
  • >> is similar, but for the input.
  • endl is an abbreviation for end of line.
    cout<<endl; does the same as cout<<"/n";.
  • Basically, there are options to redirect the output via cout into a file, therefore, there is another output stream (I might come back to this later), to be used with cerr instead of cout. This is then mainly used for error warnings etc..
The key point in the handling of input and output is that it is connected to a so-called stream, and to a device. This device might be the screen, a file etc., and according to what it is, different data types might have different representations. Hence, within the iostream.h there's a lot of defintions of how to represent different data types and options for the manipulation thereof. I would like to note in passing that for every class you could define a specific way of representing it when you want to output it. In other words, you could do something along the lines of
#include <iostream.h>

...
    cout<<my_class<<endl
...

provided that you defined the representation of your class for output.

[prev] [top] [next]