SIMPLE INPUT AND OUTPUT

Aims

To enable students to:

 ·	describe the cin standard input stream

 ·	perform operations on the standard input stream 

 ·	describe the cout standard output stream 

 ·	perform operations on the standard output stream 

Describe the cin standard input stream

A program communicates with its environment by reading from and writing to files (ordered sequences of bytes). A file includes, a data set that you can read and write repeatedly (such as a disk file) or a stream of bytes received from or sent to a peripheral device (such as the keyboard or display). 

You manipulate these files in much the same way -- by calling library functions. By including the header file iostream.h a source file can declare objects that control reading from and writing to the standard input and output streams. This is the only header needed to enable a C++ program to perform simple input and output.

Example program to input a character

#include <iostream.h>
void main ()
{
      char cInput;
      cin >> cInput;
}

cin represents an input device (the keyboard), >> (the extraction operator) instructs the computer to read information and place it into the variable cInput (of type char). By changing the type of the variable from char to int the same code will read integer values, not characters. Besides reading single values into single variables, cin can be used to fill arrays (i.e. contiguous blocks of memory). In the following example an array 100 elements long of type char is used to store a line of text entered by the user.

#include <iostream.h>
void main ()
{
      char cInput [100];
      cin >> cInput;
}

It is also possible to chain extraction operators together, as follows:

#include <iostream.h>
void main ()
{
      char cInput;
      float fInput;
      int iInput;

      cin >> cInput >> fInput >> iInput;
}

The extraction operator will pull characters from the input stream, breaking them up into units based on white characters (space, tab or newline) and copying these units into their associated variables. By passing the values “a 27.2 33” into the example program cin will assign the values a to cInput, 27.2 to fInput and 33 to iInput, breaking the input stream up by spaces.
Perform operations on the standard input stream

The code presented so far will read characters from the standard input stream until a new line character is encountered (by pressing the enter key). This can have disastrous consequences, in the code fragment above we have allocated enough memory to store 100 characters, if the user of the program enters 200 characters and then presses enter the >> operation will copy too many characters into the cInput array, overwriting whatever is in the adjacent memory locations. Fortunately cin provides a function, getline, that permits the programmer to specify the maximum number of characters to read from the keyboard. The getline function requires two pieces of information, the character array into which to write the information from the keyboard and how many characters to copy (the character array size), for example:

#include <iostream.h>
void main ()
{
      char cInput [100];
      cin.getline( cInput, 100 );
}

The >> operation and getline function both result in user input being echoed to the screen. This may not always be desirable, by using the function getch, as found in conio.h, it is possible to obtain input from the keyboard without echoing the characters to screen, as demonstrated below:

#include <conio.h>
void main ()
{
      char cInput;
      cInput = getch ();
}

The getch function can also be used to pause a programs execution until the user presses a key as the value returned by the function does not need to be stored.

Frequently programs need to read in character values from a user and convert them to their numeric form for internal processing. The file stdlib.h contains prototypes for functions which permit character arrays to be converted to integers or floats. The function atoi takes in an array of characters and returns an integer value, while atof returns a float. For example:

#include <stdlib.h>
void main ()
{
      int iValue;
      iValue = atoi (“1234”);
}

would result in the variable iValue containing the value 1234.

Describe the cout standard output stream

Just as with cin the standard output stream communicates with a peripheral device, in this case the display terminal allowing programs to communicate with their operators.

Example program to output the character ‘A'

#include <iostream.h>
void main ()
{
      char cOutput = ‘A’;
      cout << cOutput;
}

cout represents an output device (the display), << (the insertion operator) instructs the computer to write information contained in the variable cOutput (of type char) to the display. 

All values passed to cout (whether, character variable, numeric variable, string or constant) are displayed as strings, the insertion operator being capable of converting all standard C++ data types (e.g. char, int, float, etc.) where necessary. As with cin it is possible to chain insertion operators, as demonstrated below:

#include <iostream.h>
void main ()
{
      int iValue = 1000;

      cout << 25 << “ string ” << iValue;
}

resulting in the following output:

25 string 1000

Perform operations on the standard output stream 

Programs often need to have exact control    over their output, for example ensuring all number appear in block at least ten characters wide. cout provides facilities to manipulate the appearance of data on screen though stream manipulators, the following code will ensure all the numbers provided appear right justified in fields ten characters wide:

#include <iostream.h>
void main ()
{
      cout.width (10);
      cout << 12345;
      cout.width (10);
      cout << 47;
      cout.width (10);
      cout << 12345678;
}

producing    12345        47  12345678 on the screen.

Other formatting options are available. In the previous example fields were filled with spaces where a number was not big enough, it is possible for other charters to be specified, such as ‘.’as shown below:

#include <iostream.h>
void main ()
{
      cout.fill (‘.’);
      cout << “total amount due”;
      cout.width (20);
      cout << “£1024.64”;
}

resulting in    total amount due............£1024.64

To control justification the constants ios::left and ios::right can be employed. The code below ensures all the numbers provided appear left justified in fields ten characters wide, padded with ‘.’ where appropriate:

#include <iostream.h>
void main ()
{
      cout.fill ('.');
      cout.flags (ios::left);
      cout.width (10);
      cout << 12345;
      cout.width (10);
      cout << 47;
      cout.width (10);
      cout << 12345678;
}

resulting in 12345.....47........12345678.. being displayed.

Note, setting the width affects only the output generated by the next insertion operation, the width then reverts to its default value. With other formatting features the new behaviour remains in effect until explicitly changed. 

Strings themselves can contain special character sequences (termed escape sequences) that are interpreted and displayed specially. These sequences can exist on their own or embedded within other strings. Escape sequences begin with a \. The following sequences will be discussed; \n (new line), \t (tab), \\ (backslash), \”    (quote mark) and \a (bell) - note, other escape sequences exist.

All the examples provided so far display information on a single line. This would prove very limiting for real applications. By including “\n” within the string passed to cout it is possible to introduce a new line into the output stream, for example:

#include <iostream.h>
void main ()
{
      cout << “Rain fall:\n”
      cout.width (10);
      cout << 123.45;
      cout << “\n”
      cout.width (10);
      cout << 47;
      cout << “\n”
      cout.width (10);
      cout << 356.78;
}

produces the following output

Rain fall:
        123.45
                47
        356.78

The \t sequence introduces a tab character, the following code generates the output Hello   world

#include <iostream.h>
void main ()
{
      cout << "Hello\tworld";
}

A problem may have become apparent. If a \ is used to indicate the beginning of an escape sequence, how is a \ ever displayed on the screen. The solution is to place \\ into the string, as in cout << “Hello\\world”; which results in Hello\world being displayed. 

Likewise, strings are delimited by quote marks (“) - how are they to be displayed on the screen? The answer is to precede them by a \, as in 

#include <iostream.h>
void main ()
{
      cout << "Hello\”world\”";
}

which result in Hello ”world” being displayed.

To generate a beep within a program send the escape sequence \a to cout.