C++ Programming Simple Program Components

advertisement

C++ Programming

Simple Program Components

Before developing your first C++ program, it is necessary to understand how to use many of the require components. The correct use of these required components will enable you to successfully develop C++ program.

Program Organization

Here's how your source file is usually arranged. Preprocessor directives such as

#include come first, followed by class specifications, followed by main().The main() function contains statements that define objects and send messages to them. Figure 1-7 shows what this looks like.

Figure 1-7 Source file organization

In larger programs, things may be a bit more complicated. There will probably be many files. Some will contain class specifications, whereas others will hold the code that uses these classes. Nevertheless, the simple arrangement I use here reveals the essentials of OOP.

The iostream.h Header File

To use I/O streams, you need to place in the program various class specifications from which the cin and cout objects, the << and >> operators, the endl manipulator, and so on are derived. These specifications, along with various other definitions, are stored in a file called iostream.h

, which comes with your compiler. It's a text file, just like the .cpp

source files you write yourself.

To insert the iostream.h

file into your source file, place a line of text called a preprocessor directive into your code. It looks like this:

#include <iostream.h>

This directive inserts all the text from the file iostream.h

into your source file (or at least the compiler treats it as if it had been inserted; actually your source file isn't altered).

Preprocessor Directives

Preprocessor directives are instructions to the compiler . By contrast, ordinary

C++ statements, such as alpha=17; are instructions to the microprocessor, which the compiler translates into machine language that the microprocessor can understand. Preprocessor directives always start with a pound sign (#) .

When the compiler encounters the #include preprocessor directive shown above, it starts to search for the file iostream.h

. There is a particular subdirectory where such files are stored, usually called ...\include\ (where the dots represent the first part of the path name, such as c:\bc5). This subdirectory is usually found in the general directory for the compiler you're using. The compiler should know where such a directory is located; if not, it may need to be told (see the appendix in this book that applies to your particular compiler). Once it finds the file, the compiler

(actually a part of the compiler called the preprocessor) simply inserts its text into the source file in place of the #include directive.

If you want to see what's in iostream.h

, you can go to the ...\include\ directory and examine it with the compiler's editor or any other text editor. (Be careful not to change the file.) The contents won't make much sense at this point, but you will at least prove to yourself that iostream.h

is a text file, written in normal ASCII characters.

There are other preprocessor directives besides #include; you'll encounter a few more as you go along.

I should note that there are two formats for specifying the file in an #include directive. Using the appropriate format speeds up the compiler's search for the file. In the example above, angle brackets are used to delimit the file name.

#include <filename.ext>

This causes the compiler's search for the file to start in the standard ...\include\ directory. If quotes are used instead

#include "filename.ext" then the search for the file will begin in the directory where the program's source files are stored.

Other Header Files

There are many header files. Some are used with the C function library . For example, if you need to use mathematical functions such as sin() and cos() , you need to include a header file called math.h

. If you're going to operate on strings, you'll need string.h

; if you're going to perform certain kinds of data conversion, you may need to include stdlib.h

. Various specialized I/O functions may require conio.h

or stdio.h.

Other header files are needed for other kinds of class specifications. For example, your compiler may be bundled with a container class library. Container is a general name for a data structure, such as an array, a stack, a queue, or a linked list. The container class library contains classes that model these data structures, but if you want to use one, you'll need to include a header file specific to the particular container, such as arrays.h, stacks.h, or queues.h.

Don't worry if there seems to be an endless number of header files. All you really need to know about header files at this point is that they are an important part of

C++ programs and you'll need to include iostream.h

to run any program that does stream I/O.

The main() Function

Everything must have a beginning, and your program begins executing in a function called main().

This is not a member function of a class; it's a special standalone function to which control is transferred from the operating system. The first statement in main(), whatever it may be, is the first statement in your program to be executed.

Here's how main() looks when it has no statements installed in it:

void main()

{

}

Every program must contain a main() function . If it doesn't, you'll get error messages from the linker when you try to compile and link your program.

Above I show main() with a return type of void. You can also use a return type of int. When you do, the value returned is a code, which is usually used to indicate whether the program ran successfully. (This is useful for batch files.) The example programs in this book don't return a code, so the return type of main() will always be void. You don't need to worry about return types now anyway.

The main() function can also take arguments, which are used when a program is called from the command line and has extra text, such as a file name, typed after the program name. However, I'll ignore this possibility as well.

Output to the Screen

Here's a statement that causes a line of text to be displayed on the screen:

cout << "This text will appear on the screen.";

The name cout , pronounced "C out," represents a C++ object that is associated with the screen display . The << operator, called the put to operator , causes whatever is on its right to be sent to whatever is on its left. The cout object and the << operator are part of the C++ standard stream library, so you don't need to define them yourself or even worry too much about how they work. (You will need to insert a header file into your program to declare them, as you'll see in the next chapter.) Figure 1- 8 shows how cout works.

Figure 1-8 Output with cout

String Constants

The text "This text will appear on the screen." is called a string constant . A string constant is surrounded by double quotes (unlike a character constant, which is surrounded by single quotes). The entire statement, as with all C++ statements, is terminated with a semicolon .

You can output numerical constants the same way. The statement

cout << 27; causes a 27 to appear on the screen, whereas

cout << 123.45; displays 123.45.

You can display the values of variables as well as numbers. For example, this code displays 2.7:

float fvar1 = 2.7; cout << fvar1;

More than one value can be displayed with a single cout statement, using multiple put to operators:

float height = 2.7; cout << "It is " << height << " meters high.";

This would produce the output

It is 2.7 meters high.

You can also reformat such a statement so that the put to operators line up vertically, thus making the statement easier to read:

cout << "It is "

<< height

<< " meters high.";

Or you could use three separate cout statements to produce the same output.

Formatting Output

It's nice to have some control over the way output is formatted. In C++ stream

I/O, a variety of techniques are available for this purpose. I'll show two examples here.

New Lines Not Automatic

Some languages, such as BASIC, automatically move to a new line at the end of every output statement, but C++ does not. Nor are different variables in the same statement placed on separate lines. New lines are not created automatically by the cout object or the put to operator. For example, the statements

cout << 6.25; cout << 30.9 << 2.5; produce the output

6.2530.92.5

where all the output is run together. This is probably not what you want.

Escape Sequences

One of the easiest ways to format data is to insert a character called an escape sequence into a string constant. For example, you can use the '\n' escape sequence to start a new line:

cout << "\nNow I'll ask you some questions about

yourself."; cout << "\nFirst, enter your age: "; produces the display

Now I'll ask you some questions about yourself.

First, enter your age:

The '\n' before "First" causes the second string constant to be displayed on a separate line from the first. (The '\n' before "Now" ensures that the first line begins on a new line as well, even if something else has already been printed by a preceding statement.)

You can use the escape sequence '\t' to generate tab characters. The code

cout << "\nJoe\tFred\tSally"; cout << "\nGeorge\tBud\tSandy"; lines up the names in columns.

Joe Fred Sally

George Bud Sandy

The endl Manipulator

There's another approach to starting new lines in C++. An object called a manipulator can be inserted into an output stream, just like a data item.

Manipulators can be used to format output, among other purposes. Probably the most common manipulator is endl (a contraction of "end line"). Inserted into a cout statement, endl causes the cursor to move to the start of the next line, just as

'\n' does. (Also, endl flushes any output that may be waiting in the output buffer to the display.)

Earlier, I showed two lines that used the '\n' escape sequence to start text on a new line. Here's how to achieve the same result using endl:

cout << endl;

cout << "Now I'll ask you some questions about

yourself." << endl; cout << "First, enter your age: ";

The first statement ensures you start on a new line and the endl at the end of the second statement causes the text beginning with "First" to start on a new line.

Input from the Keyboard

Here's how to input a number, entered by the user from the keyboard, and store it in a variable intvar:

int intvar; cin >> intvar;

The cin object (for "C in") represents the keyboard, and the get from operator

( >> ) takes whatever is on the left and puts it in the variable on the right. When this statement is executed, the program waits for the user to type a number and press [ENTER]. Figure 1-9 shows how this looks.

Figure 1-9 Input with cin

Usually, of course, you want to prompt the user before waiting for input:

int age;

cout << "Enter your age: "; cin >> age;

This produces the following interaction:

Enter your age: 34 where the user enters the 34.

You can use the get from operator multiple times in the same statement:

int age;

float height;

cout << "Enter your age and height: "; cin >> age >> height;

Here the user presses [ENTER], [SPACE], or [TAB] after each value before entering the next one. However, it's usually better to prompt the user for only one value at a time, to avoid any possibility of confusion.

Download