Standard Input and Output
Input can come from keyboard, disk file, or other source.
Output can go to the screen, disk, printer, etc.
In C++ cout writes by default to "standard output" which is preset to be the screen
In C++ cin reads by default from "standard input" which is preset to be the keyboard.
I/O Redirection
We can change these presets when we run a program using "I/O redirection". We can change the place where standard input comes from and the place where standard output goes to for a given run of the program.
As an example, suppose a program reads lines of the form:
HENRY, JIM
MOORE, MARY
DOE, JOHN
these could be typed in at the keyboard. OR, we could use a word processor like Notepad (or the Quincy Editor) to type them in and store them in a file. Then the program could read from the file (instead of from the keyboard) by redirecting the input. It works like this:
Assume the file with these names in it is called names.dat and is stored on your a: drive.
Follow these steps:
1. Compile and Build your program in IDE.
Assume your program source code is called pgm.cpp:
2. Use Windows to get a DOS command prompt window. If you are using XP, you can
3. At the DOS prompt, make sure that the prompt shows the drive letter and path where your program is. You can change the drive by typing the drive letter and a colon:
a: or c: or f:
You can change the path (i.e. the subdirectory or folder you want) via the cd command:
cd quincy2002\mypgms
or whatever.
4. Check that the .exe file is there: type
dir
and look for pgm.exe
5. To run the program so it reads from the keyboard, at the DOS prompt, type:
pgm
to run the program so it reads from the file, at the DOS prompt, type:
pgm < a:names.dat
The "<" symbol is the input redirection symbol. It's visual shape reminds you that data is going from names.dat into pgm.
To redirect output, use the > sign. So if you wanted your program
to read from names.dat and write output to new.dat,
type:
a: pgm < a:names.dat > a:new.dat
When your program has completed, you will see the DOS prompt again. If you are finished, you can get rid of the Command Prompt window by typing
exit
If you will be running the program again, you can just leave it open.
Notice that although your program will work as before using redirected I/O sometimes it may appear not to. For example, suppose your program needs to prompt the user to enter an interest rate (a number) and then it will calculate and display a table of compound interest. The prompt as well as the display will use cout. When you run the program with standard output to the screen, everything is fine. You see the prompt and then the table of results. Now suppose you want to store the table in a disk file so you can view it later or print it. So you redirect output to a file as shown above.
What happens when you run the program? You see nothing on the DOS screen. The prompt for an input interest rate has been written to the file and the program is waiting for you to type a number. If you know this, you can just type the number and then the program will go ahead and do the calculations and and write the results to disk. You can look at them later. And the program will terminate and you will get your DOS prompt back.
But clearly this is not a graceful way to write this program. Later we
will study ways so you can have both screen and file output.
Scalar Data Types
Any data type whose variables can take on a set of values whose number is no greater
than the number of integers representable on the computer is called a scalar data type.
int, long int, and char are scalars. Strings and floats and doubles are not.
More on the char Data Type
We have seen that C++ has a built-in data type to represent single characters. It is one of the fundamental data types of the language.
Internally, a character is represented by a numeric code in the range of 0 to 255. (32 to 127 are standard; some of 0 to 31 and all of 128 to 255 depend on the computer you use.)
So char is a scalar - there are only 256 possible values. Each char is associated with an integer value. In fact, in C++ chars can be usually be treated as integers (!). This is unusual since usually C++ does not permit us to mix data types. We will see some examples of this below.
To review:
The data type name is char. To declare a char variable:
char ch;
A char literal is written with single quotes around it: 'a'
cout knows how to display char data:
char ch = 'a';
cout << ch;
Some special cases:
A backslash char is written: '\\' - single quote, backslash, backslash, single quote
A single quote char is written as: '\'' - single quote, backslash, single quote, single quote
A double quote char is written as: '\"' - single quote, backslash, double quote, single quote
The common "escape sequence" characters (newline, tab, etc.) are also written with single quotes, but are still typed with the leading \: '\n'
ch = '\n'; //stores newline char in ch
Other chars with no keyboard representation are written in base 8 using three digits: '\007'. This is not covered further in this course.
The ASCII Character Set
This is a standard mapping of integer values to characters, used by most computer systems (exception - IBM mainframes).
Some useful ones to know (i.e. memorize these for this course)
blank = 32 digit '0' = 48 digit '9' = 57 'A' = 65 'Z' = 90 'a' = 97 'z' = 122
Note: '1' is 49, '2' is 50, etc. so if you know '0' you know all the digits. 'B' is 66, 'C' is 67, 'b' is 98, 'c' is 99, etc. so you can figure out any letter, too.
Since chars are really small ints (internally) we can do some useful tricks with them by treating them as integers.
char ch = 'A'; int i;
//print Ascii value of ch (65). Note the typecast cout << (int) ch; // print ASCII values of A..Z for (i = 'A'; i <= 'Z'; i++) cout << "\nASCII value of " << (char) i << " is " << i;
will print:
ASCII value of A is 65
ASCII value of B is 66
ASCII value of C is 67
etc.
Character functions
There is a set of standard C++ functions to test whether a character is of a certain kind (capital, lower case, digit, punctuation, whitespace, etc.) These are accessed via a library <ctype.h> which is automatically included in the Quincy C++ IDE.
For example, if you want to test if a character entered by the user is a digit, you can call
if (isdigit(ch)) // ch is a char varaible
There are also two functions to change a char from upper to lower or from lower to upper: (toupper() and tolower())
Suppose you have a single char
(not a string) from the user. If it is 'q' or 'Q' that signals quit. Before we
had to code something like:
while (ch != 'q' && ch != 'Q')
{
// do something
}
Now we could do this:
while (toupper(ch) != 'Q')
{
// do something
}
In other words, ch is converted to upper case and the result of that is compared to 'Q'.
Notice, too, that we can compare chars with !=, = =, <=, etc. just like numbers (since they are small ints).
More on Decision Structures
We have studied and used the if statement to implement the idea of a decision.
There are a couple more ways in C++ to implement decisions that you should know about.
1. switch
The switch statement can cause 0 to many alternative blocks of code to execute based on the value of a scalar variable (an int or a char ...). Switch will not work on non-scalars like strings or doubles.
Normally it is used to execute one and only one block of code.
Example:
int n;
n = some value;
switch (n) //go to case that matches n's value
{
case 1: //if n == 1, these execute
stmt;
stmt;
break; //go to stmnt after closing }
case 3:
stmnt;
break;
case 5:
stmnt;
stmnt;
break;
default: //n not 1, 3, 5: this executes
stmnt;
stmnt;
}
The default block is optional.
Sometimes you want to do the same thing for several values. You can do this:
char ch; string s;
ch = some value;
switch (ch)
{
case 'a':
case 'b':
case 'c':
case 'd':
s = "pass";
break;
case 'f':
s = "fail";
break;
case 'i':
case 'n':
case 'w':
s = "other";
break;
default:
s = "invalid";
}
If ch is 'b', for example, it will match case 'b' and go there - then just "fall through" the case 'c', case 'd', assign "pass" to s, and then break out of the switch structure.
Note: forgetting a break is a common error. If you forget a break, execution will "fall through" and execute all code after it until it finally hits a break or finishes all the code in the switch.
2. Use of the ? and : operators - a "ternary" instruction
A short and somewhat cryptic decision structure is allowed by C++. The general format is:
(condition) ? stmnt_to_do_if_true : stmnt_to_do_if_false;
Some compilers do not require the () around the condition.
As an example:
(x < y) ? x++ : y++;
This is the same as writing:
if (x < y) x++; else y++;
But there is one difference. The expression as a whole becomes the value computed in one of the two "branches". Here are a couple of examples. Note the () around the whole ternary expression:
char ch = 'y'; int x = 3, y = 2; cout << ((ch == 'y') ? "Yes" : "No"); cout << "The value of the smaller of x and y is " << ((x < y) ? x : y);
and this would display "YesThe value of the smaller of x and y is 2" This somewhat terse syntax can be handy sometimes.