Conditional Controls

Chapter 5 - C and C++ Programming

Visual C++ 6: The Complete Reference
Chris H. Pappas and William H. Murray, III
  Copyright 1998 The McGraw-Hill Companies

Fundamental Components for a C/C++ Program
You may have heard that C is a difficult language to master. However, while it is true that a brief encounter with C code may leave you scratching your head, this is only due to C’s foreign syntax, structure, and indentation schemes. By the end of this chapter, you should have enough information to have developed a working knowledge of the C language that enables you to write short but meaningful code. In the next section, you will learn about the five fundamental components of a “good” program.
Five Elements of Good C Program Design
You may be familiar with a problem-solution format called an IPO diagram. IPO diagrams were a stylized approach to the age-old programming problem of input/process/output. The following list elaborates on these three fundamentals and encapsulates the entire application development cycle. All programs must address the following five components:
  1. Programs must obtain information from some input source.
  2. Programs must decide how this input is to be arranged and stored.
  3. Programs use a set of instructions to manipulate the input. These instructions can be broken down into four major categories: single statements, conditional statements, loops, and subroutines.
  4. Programs must report the results of the data manipulation.
  5. A well-written application incorporates all of the fundamentals just listed, expressed by using good modular design, self-documenting code (meaningful variable names), and a good indentation scheme.
A Simple C Program
The following C program illustrates the basic components of a C application. It is suggested that you enter each example as you read about it to help you understand new concepts as you encounter them.
/*   
*   simple.c
*   Your first example C program.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>

int main( )
{
 printf(“ HELLO World! ”);

 return(0);
}
There is a lot happening in this short piece of code. Let’s begin with the comment block:
/*  
*   simple.c
*   Your first example C program.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/
All well-written source code includes meaningful comments. A meaningful comment is one that neither insults the intelligence of the programmer nor assumes too much. In C, comments begin with /* and are terminated with */. Anything between these unique symbol pairs is ignored by the compiler.
The next statement represents one of C’s unique features, known as a preprocessor statement.
#include <stdio.h>
A preprocessor statement is like a precompile instruction. In this case, the statement instructs the compiler to retrieve the code stored in the predefined STDIO.H file into the source code on the line requested. (The STDIO.H file is called a header file. Header files can include symbolic constants, identifiers, and function prototypes, and have these declarations pulled out of the main program for purposes of modularity.)
Following the #include( ) statement is the main function declaration:
int main( )
{
 .
 .
 .
 return(0);  /
*   or return 0;  */
}
All C programs are made up of function calls. Every C program must have one called main( ). The main( ) function is usually where program execution begins, and it ends with a return( ) from the main( ). The int to the left of main( ) defines the function’s return type, in this case integer, and explains why the return( ) statement contains a number inside the parentheses. A value of 0 is interpreted as meaning a successful program termination. It is also legal to use return( ) statements without the parentheses.
Following the main( ) function header is the body of the function itself. Notice the { and } symbol pairs. These are called braces. You use braces to encapsulate multiple statements. These braces may define the body for a function, or they may bundle together statements that are dependent on the same logic control statement, as is the case when several statements are executed based on the validity of an if statement. In this example, the braces define the body of the main program.
The next line is the only statement in the body of the main( ) function and is the simplest example of an output statement:
printf(“ HELLO World! ”);
The printf( ) function was previously prototyped in STDIO.H. Because no other parameters are specified, the sentence will be printed to the display monitor.
A Simple C++ Program
The example that follows performs the same function as the one just discussed, but it takes advantage of those features unique to C++:
//
//  simple.cpp
//  Your first C++ example program.
//  Copyright (c) Chris H. Pappas and William H. Murray, 1998
//

#include <iostream.h>

int main( )
{
 cout << “ HELLO World! ”;

 return(0);
}
There are three major differences between this example and the last. First, the comment designator has been changed from the /* */ pair to //. Second, the #include filename has been changed to IOSTREAM.H. The third change involves a different output operator call, cout. Many of the examples in the book will highlight the sometimes subtle and sometimes dazzling differences between C and C++.
Adding a User Interface to a C Program
The following program is a slightly more meaningful example. It is a little more complete in that it not only outputs information but also prompts the user for input. Many of the components of this program will be elaborated on throughout the remainder of the book.
/*  
*   ui.c
*   This C program prompts the user for a specified length,
*   in feet, and then outputs the value converted to
*   meters and centimeters
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>

int main( )
{
 float feet, meters, centimeters;

 printf(“Enter the number of feet to be converted: ”);
 scanf(“%f”,&feet);
 
 while(feet > 0 ) {
   centimeters = feet
* 12 * 2.54;
   meters = centimeters/100;
   printf(“%8.2f feet equals\n”, feet);
   printf(“%8.2f meters \n”,meters);
   printf(“%8.2f centimeters \n”,centimeters);
   printf(“\nEnter another value to be \n”);
   printf(“converted (0 ends the program): ”);
   scanf(“%f”,&feet);
 }
 printf(“>>> Have a nice day! <<<”);

 return(0);
}
Declaring Variables
The first thing you will notice that’s new in the program is the declaration of three variables:
float feet, meters, centimeters;
All C variables must be declared before they are used. One of the standard data types supplied by the C language is float. The syntax for declaring variables in C requires the definition of the variable’s type before the name of the variable. In this example, the float type is represented by the keyword float, and the three variables feet, meters, and centimeters are defined.
User Interaction
The next unconventional-looking statement is used to input information from the keyboard:
printf(“Enter the number of feet to be converted: ”);
scanf(“%f”,&feet);
The scanf( ) function has a requirement that is called a format string. Format strings define how the input data is to be interpreted and represented internally. The %f function parameter instructs the compiler to interpret the input as float data. In Microsoft C and C++, a float occupies 4 bytes. (Chapter 6 contains a detailed explanation of all of the C and C++ language data types.)
An Introduction to the Address Operator
In the previous statement, you may have noticed that the float variable feet was preceded by an ampersand symbol (&). The & is known as an address operator. Whenever a variable is preceded by this symbol, the compiler uses the address of the specified variable instead of the value stored in the variable. The scanf( ) function has been written to expect the address of the variable to be filled.
A Simple while Loop
One of the simplest loop structures to code in C is the while loop:
while(feet > 0) {
 .
 .
 .
}
This pretest loop starts with the reserved word while, followed by a Boolean expression that returns either a TRUE or a FALSE. The opening brace ({) and closing brace (}) are optional; they are only needed when more than one executable statement is to be associated with the loop repetition. Braced statements are sometimes referred to as compound statements, compound blocks, or code blocks.
If you are using compound blocks, make certain you use the agreed-upon brace style. While it doesn’t matter to the compiler where the braces are placed (in terms of skipped spaces or lines), programmers reading your code will certainly appreciate the style and effort. An opening loop brace is placed at the end of the test condition, and the closing brace is placed in the same column as the first character in the test condition.
Screen Output
In analyzing the second program, you will notice more complex printf( ) function calls:
printf(“%8.2f feet equals\n”, feet);
printf(“%8.2f meters \n”,meters);
printf(“%8.2f centimeters \n”,centimeters);
printf(“\nEnter another value to be \n”);
printf(“converted (0 ends the program): ”);
If you are familiar with the PL/I language developed by IBM, you will be right at home with the concept of a format or control string. Whenever a printf( ) function is invoked to print not only literal strings (any set of characters between double quote marks), but also values, a format string is required. The format string represents two things: a picture of how the output string is to look, combined with the format interpretation for each of the values printed. Format strings are always between double quote marks.
Let’s break down the first printf( ) format string (“%8.2f feet equals\n”, feet) into its separate components:
Control
Action
%8.2f
Take the value of feet, interpret it as a float, and print it in a field of eight spaces with two decimal places.
feet equals
After printing the float feet, skip one space and then print the literal string “feet equals”.
\n
Once the line is complete, execute a new line feed.
,
The comma separates the format string from the variable name(s) used to satisfy all format descriptors. (In this case, there is only one %8.2f.)
The next two printf( ) statements are similar in execution. Each statement prints a formatted float value, followed by a literal string, and ending with a new line feed. If you were to run the program, your output would look similar to this:
Enter the number of feet to be converted: 10
  10.00 feet equals
   3.05 meters
 304.80 centimeters

Enter another value to be
converted (0 stops program): 0
The C escape sequences, or output control characters, allow you to use a sequence of characters to represent special characters. Table 5-2 lists all of the output control symbols and a description of how they can be used in format strings. All leading zeros are ignored by the compiler for characters notated in hexadecimal. The compiler determines the end of a hex-specified escape character when it encounters either a nonhex character or more than two hex characters, excluding leading zeros.
Table 5-2: Output Control Symbols
Sequence
Name
Sequence
Name
\a
Alert (bell)
\?
Literal quotation mark
\b
Backspace
\’
Single quotation mark
\f
Form feed
\"
Double quotation mark
\n
Newline
\\
Backslash
\r
Carriage return
\ddd
ASCII character in octal notation
\t
Horizontal tab
\xdd
ASCII character in hex notation
\v
Vertical tab
Also on the subject of format strings—though this is a bit advanced—are the scanf( ) formatting controls. Table 5-3 describes the scanf( ) formatting controls and their meanings. If you wish to input a string without automatically appending a terminating null character (\0), use %nc, where n is a decimal integer. In this case, the c format symbol indicates that the argument is a pointer to a character array. The next n characters are read from the input stream into the specified location, and no null character (\0) is appended. If n is not specified, the default character array length is 1.
Table 5-3: Fomat Control Symbols
Character
Input Type Expected
Argument Type
d
Decimal integer
Pointer to int
o
Octal integer
Pointer to int
x, X
Hexadecimal integer
Pointer to int
I
Decimal, hexadecimal
Pointer to int or octal integer
u
Unsigned decimal integer
Pointer to unsigned int
e, E
Floating-point value
Pointer to float
f g, G
Consisting of an optional sign
(+ or
-), a series of one or more decimal digits possibly containing a decimal point, and an optional exponent (“e” or “E”) followed by an optionally signed integer value
c
Character. White-space characters that are ordinarily skipped are read when c is specified; to read the next nonwhite-space character, use %1s
Pointer to char
s
String
Pointer to character array autocreate NULL string
n
No input read from stream or buffer
Pointer to int, into which is stored the number of characters read from the stream or buffer up to that point in call to scanf( )
p
In the form xxxx:yyyy, where x digits and y digits are uppercase hexadecimal digits
Pointer to far; pointer to void
As you learn more about the various C data types, you will be able to refer back to Tables 5-2 and 5-3 for a reminder of how the different controls affect input and output.
Using the Integrated Debugger
To examine the actual operation of the C code presented in this section, you can use the integrated debugger. When you compile your program, make certain you have turned on debug information. This is done in conjunction with the Project utility. Once your application is compiled and linked, use the debugger to keep an eye on the variables yard, feet, and inch.
Adding a User Interface to a C++ Program
The following C++ example is identical in function to the previous C example except for some minor variations in the syntax used:
//
//  ui.cpp
//  This C++ program prompts the user for a specified length,
//  in feet, and then outputs the value converted to
//  meters and centimeters.
//  Copyright (c) Chris H. Pappas and William H. Murray, 1998
//

#include <iostream.h>
#include <iomanip.h>

int main( )
{
 float feet,meters,centimeters;

 cout << “Enter the number of feet to be converted: ”;
 cin  >> feet;
 while(feet > 0 ) {
   centimeters = feet
* 12 * 2.54;
   meters = centimeters/100;
   cout << setw(8) << setprecision \
        << setiosflags(ios::fixed) << feet << “ feet equals \n”;
   cout << setw(8) << setprecision \
        << meters << “ meters \n”;
   cout << setw(8) << setprecision \
        << centimeters << “ centimeters \n”;
   cout << “\nEnter another value to be \n”;
   cout << “converted (0 ends the program): ”;
   cin >>  feet;
 }
 cout << “>>> Have a nice day! <<<”;

 return(0);
}
There are six major differences between the C++ example and its C counterpart. The first two changes involve the use of cin and cout for I/O. These statements use the << (“put to,” or insertion) and >> (“get from,” or extraction) iostream operators. Both operators have been overloaded to handle the output/input of all the predefined types. They can also be overloaded to handle user-defined types such as rational numbers.
The last four changes are all related to formatting C++ output. To gain the same output precision easily afforded by C’s “%8.2f” format string, the program requires four additional statements. The file IOMANIP.H is included in the program to give access to three specific class-member inline functions: setw( ), setprecision( ), and setiosflags( ). As you look at the code, you will notice that the calls to setw( ) and setprecision( ) are repeated. This is because their effect is only for the next output value, unlike setiosflags( ), which makes a global change to fixed output.
C++ programmers who like the power and flexibility of the C output function printf( ) can use printf( ) directly from library STDIO.H. The next two statements show the C and C++ equivalents:
printf(“%8.2f feet equals\n”, feet);
cout << setw(8) << setprecision \
    << setiosflags(ios::fixed) << feet << “ feet equals \n”;
Adding File I/O
Of course, there will be times when an application wants either its input or output, rather than the keyboard and display monitor, to deal directly with files. This brief introduction serves as an example of how to declare and use simple data files:
/*
*   file1.cpp
*   This C++ program demonstrates how to declare and use both
*   input and output files. The example program
*   takes the order_price from customer.dat and generates
*   a billing_price that is printed to billing.dat.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>
#define MIN_DISCOUNT .97
#define MAX_DISCOUNT .95

int main( )
{
 float forder_price, fbilling_price;
 FILE *fin,*fout;
    
 fin=fopen(“a:\\customer.dat”,"r");
 fout=fopen(“a:\\billing.dat”,"w");

 while (fscanf(fin,"%f",&forder_price) != EOF) {
   fprintf(fout,"Your order of \t\t$%8.2f\n", forder_price);
   if (forder_price < 10000)
      fbilling_price = forder_price * MIN_DISCOUNT;
   else fbilling_price = forder_price * MAX_DISCOUNT;
   fprintf(fout,"is discounted to \t$%8.2f.\n\n",
           fbilling_price);
 }
 return(0);
}
Each file in a C program must be associated with a file pointer, which points to information that defines various things about a file, including the path to the file, its name, and its status. A file pointer is a pointer variable of type FILE and is defined in STDIO.H. The following statement from the example program declares two files, *fin and *fout:
, FILE *fin,*fout;
The next two statements in the program open two separate streams and associate each file with its respective stream:
fin=fopen(“a:\\customer.dat”,"r");
fout=fopen(“a:\\billing.dat”,"w");
The statements also return the file pointer for each file. Since these are pointers to files, your application should never alter their values.
The second parameter to the fopen( ) function is the file mode. Files may be opened in either Text or Binary mode. When in Text mode, most C compilers translate carriage return/linefeed sequences into newline characters on input. During output, the opposite occurs. However, binary files do not go through such translations. Table 5-4 lists all of the valid file modes.
Table 5-4: Valid C File Modes
Access Type
Description
a
Opens in Append mode. It creates the file if it does not already exist. All write operations occur at the end of the file.
a+
Same as above, but also allows reading.
r
Opens for reading. If the file does not exist or cannot be found, the open call will fail.
r+
Opens for both reading and writing. If the file does not exist or cannot be found, the open call will fail.
w
Opens an empty file for writing. If the file exists, all contents are destroyed.
w+
Opens an empty file for both reading and writing. If the file exists, all contents are destroyed.
The r+, w+, and a+ file modes select both reading and writing. (The file is open for update.) When switching between reading and writing, you must remember to reposition the file pointer, using either fsetpos( ), fseek( ), or rewind( ).
C does perform its own file closing automatically whenever the application closes. However, there may be times when you want direct control over when a file is closed. The following listing shows the same program modified to include the necessary closing function calls:
/*
*   file1.c
*   This C program demonstrates how to declare and use both
*   input and output files. The example program
*   takes the order_price from customer.dat and generates
*   a billing_price that is printed to billing.dat
*   Copyright (c) Chrisf H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>
#define MIN_DISCOUNT .97
#define MAX_DISCOUNT .95

int main( )
{
 float forder_price, fbilling_price;
 FILE
*fin,*fout;
    
 fin=fopen(“a:\\customer.dat”,"r");
 fout=fopen(“a:\\billing.dat”,"w");

 while (fscanf(fin,"%f",&forder_price) != EOF) {
   fprintf(fout,"Your order of \t\t$%8.2f\n", forder_price);
   if (forder_price < 10000)
      fbilling_price = forder_price
* MIN_DISCOUNT;
   else fbilling_price = forder_price
* MAX_DISCOUNT;
   fprintf(fout,"is discounted to \t$%8.2f.\n\n",                        fbilling_price);
 }

 fclose(fin);
 fclose(fout);

 return(0);
}
The following program performs the same function as the one just examined, but is coded in C++:
//
//  file2.cpp
//  This C++ program demonstrates how to declare and use both
//  input and output files. The example program
//  takes the order_price from customer.dat and generates
//  a billing_price that is printed to billing.dat.
//  Copyright (c) Chris H. Pappas and William H. Murray, 1998
//

#include <fstream.h>
#include <iomanip.h>
#define MIN_DISCOUNT .97
#define MAX_DISCOUNT .95

int main( )
{
 float forder_price, fbilling_price;
 ifstream fin(“a:\\customer.dat”);
 ofstream fout(“a:\\billing.dat”);

 fin >> forder_price;
 while (!fin.eof( )) {
   fout << setiosflags(ios::fixed);
   fout << “Your order of \t\t$” << setprecision \
        << setw(8) << forder_price << “\n”;
   if (forder_price < 10000)
      fbilling_price = forder_price
* MIN_DISCOUNT;
   else fbilling_price = forder_price
* MAX_DISCOUNT;
   fout << “is discounted to \t$” << setprecision \
        << setw(8) << fbilling_price << “.\n\n”;
   fin >> forder_price;
 }

 fin.close( );
 fout.close( );

 return(0);
}
Disk file input and output are slightly different in C++ than in C. C++ has a two-part design to its stream library: a streambuf( ) object and a stream. This same model performs I/O for keyboard and terminal as well as disk I/O. The same operators and operations perform in precisely the same way. This greatly simplifies a programming task that has always been difficult and confusing. To facilitate disk file I/O, the stream library defines a filebuf( ) object, which is a derivative of the standard streambuf( ) type. Like its progenitor type, filebuf( ) manages a buffer, but in this case, the buffer is attached to a disk file. You will learn more about files in Chapter 11.

Books24x7.com, Inc 2000 –  


Visual C++ 6(c) The Complete Reference
Visual Studio 6: The Complete Reference
ISBN: B00007FYGA
EAN: N/A
Year: 1998
Pages: 207

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net