Thursday, September 27, 2007

Basic Input/Output Operations

Basic Input/Output Operations
C++ input/output revolves around the notion of a data stream, where we can insert data into an output stream or extract data from an input stream. We have already seen that the standard output stream to the screen is referred to as cout. The input stream from the keyboard is referred to as cin.
Input from the Keyboard
We obtain input from the keyboard through the stream cin, using the extractor operator for a stream, >>. To read two integer values from the keyboard into integer variables num1 and num2, you can write this:cin >> num1 >> num2;
The operator 'points' in the direction that data flows - in this case, from cin to each of the two variables in turn. Any leading whitespace is skipped and the first integer value you key in is read into num1. This is because the input statement executes from left to right. Whitespace following num1 is ignored and the second integer value that you enter is read into num2. There has to be some whitespace between successive values though, so that they can be differentiated. The stream input operation ends when you press the Enter key and execution then continues with the next statement. Of course, errors can arise if you key in the wrong data, but we will assume that you always get it right!
Floating point values are read from the keyboard in exactly the same way as integers and, of course, we can mix the two. The stream input and operations automatically deal with variables and data of any of the basic types. For example, look at the statements,int num1 = 0, num2 = 0;
double factor = 0.0;
cin >> num1 >> factor >> num2;
The last line will read an integer into num1, then a floating point value into factor and, finally, an integer into num2.
Try It Out - Output to the Display
Writing information to the display operates in a complementary fashion to input. The stream is called cout and we use the insertion operator, <<. This also 'points' in the direction of data movement. We have already used this operator to output a text string between quotes. We can demonstrate the process of outputting the value of a variable with a simple program. We'll assume that you've got the hang of creating a new project and a new source file, adding the source file to the project and building it into an executable. Here's the code:// EX1_02.CPP
// Exercising output
#include
using namespace std;
int main()
{
int num1 = 1234, num2 = 5678;
cout << endl; //Start on a new line
cout << num1 << num2; //Output two values
cout << endl; //End on a new line
return 0; //Exit program
}

How It Works
The first statement in the body of main() declares and initializes two integer variables, num1 and num2. This is followed by two output statements, the first of which moves the screen cursor position to a new line. Because output statements execute from left to right, the second output statement displays the value of num1 followed by the value of num2.
When you compile and execute this, you will get the output:
This is correct, but not exactly helpful. We really need the two output values to be separated by at least one space. The default for stream output is to just output the digits in the output value, which doesn't provide for spacing different values out nicely, so they can be differentiated. As it is, we have no way to tell where the first number ends and the second number begins.
Try It Out - Manipulators
We can fix this quite easily, though, just by outputting a space between the two values. We can do this by replacing the following line in our original program:cout << num1 << num2; //Output two values
with the statement:cout << num1 << ' ' << num2; //Output two values
Of course, if we had several rows of output that we wanted to align in columns, we would need some extra capability, as we do not know how many digits there will be in each value. We can take care of this situation by using what is called a manipulator. A manipulator modifies the way in which data output to (or input from) a stream is handled.
Manipulators are defined in the header file iomanip, so we need to add a #include statement for it. The manipulator that we will use is setw(n), which will output the following value right-justified in a field n spaces wide, so setw(6) puts the output in a field with a width of six spaces. To get something more like the output we want, we can change our program to the following:// EX1_03.CPP
// Exercising output
#include
#include
using namespace std;
int main()
{
int num1 = 1234, num2 = 5678;
cout << endl; //Start on a new line
cout << setw(6) << num1 << setw(6) << num2; //Output two values
cout << endl; //Start on a new line
return 0; //Exit program
}
Note that the highlighted lines indicate the code that has changed compared to the previous example.
How It Works
The only changes from the last example are the addition of the #include statement for the file iomanip, and the insertion of the setw() manipulator in the output stream preceding each value, to output the values in a field six characters wide. Now we get nice neat output where we can actually separate the two values:
Note that the setw() manipulator only works for the single output value immediately following it. We have to insert it into the stream immediately preceding each value that we want to output within a given field width. If we put only one setw(), it would apply to the first value to be output after it was inserted. Any following value would be output in the default manner. You could try this out by deleting the second setw(6) and its insertion operator in the above example.
Escape Sequences
When we write a character string between quotes, we can include special characters called escape sequences. They are called escape sequences because they allow characters to be included in a string that otherwise could not be represented. An escape sequence starts with a backslash character, \. For example, a tab character is written as \t, so these two output statements,cout << endl << "This is output.";
cout << endl << "\tThis is output after a tab.";
will produce these lines:
This is output.
This is output after a tab.
In fact, instead of using endl, we could include the escape sequence for the newline character, \n, in each string, so we could rewrite the statements above as follows:cout << "\nThis is output.";
cout << "\n\tThis is output after a tab.";
Here are some escape sequences which may be particularly useful:
Escape sequence
What it does
\a
sounds a beep
\n
newline
\'
single quote
\\
backslash
\b
backspace
\t
tab
\"
double quote
Obviously, if you want to be able to include a backslash or a double quote as a character to be output in a string between quotes, you must use the escape sequences to represent them. Otherwise, the backslash would be interpreted as another escape sequence and a double quote would indicate the end of the character string.
You can also use characters specified by escape sequences in the initialization of char variables. For example:char Tab = '\t'; // Initialize with tab character
That gives us enough of a toehold in input/output. We will collect a few more bits and pieces as and when we need them.

No comments: