Input and output operations

  • The most common way in which a program communicates with the outside world is through simple, character-oriented Input/Output (IO) operations. C++ provides two useful operators for this purpose: >> for input and << for output.
  • cin is used for input in C++. It is defined as an object in the header file iostream.h. The >> is the ‘extraction’ or ‘get from’ operator.
  • cout is used for output in C++. It is defined as an object in the header file iostream.h. The << is the ‘insertion’ or ‘put to’ operator.
  • cout: The cout stream is used in conjunction with the overloaded operator <<(a pair of “less than” signs).
  • cout << “Output sentence”; // prints Output sentence on screen
  • cout << 120; // prints number 120 on screen
  • cout << x; // prints the content of variable x on screen
  • The << operator is known as insertion operator since it inserts the data that follows it into the stream that precedes it.
  • In the examples above it inserted the constant string Output sentence, the numerical constant 120 and the variable x into the output stream cout.
  • Notice that the first of the two sentences is enclosed between double quotes (“it is a string of characters. Whenever we want to use constant strings of characters we must enclose them between double quotes (“) so that they can be clearly distinguished from variables.


    Cin

  • Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. This must be followed by the variable that will store the data that is going to be read. For example:
  • cin >> age;
  • Above statement waits for an input from keyboard in order to store it in the variable.
  • cin can only process the input from the keyboard once the RETURN key has been pressed.
  • Therefore, even if you request a single character cin will not process the input until the user presses RETURN once the character has been introduced.
  • You can also use cin to request more than one data input from the user:
  • cin >> a>> b; is equivalent to: cin >> a; cin>>b;
  • In both cases the user must give two data, one for variable a and another for variable b that may be separated by any valid blank separator: a space, a tab character or a new line.


Data Types << Previous

Next >> Enumerated Data Types

Our aim is to provide information to the knowledge seekers. 


comments powered by Disqus










Footer1