7.4 The Prototype

I l @ ve RuBoard

Once the code design is completed, you can begin writing the program. But rather than try to write the entire program at once and then debug it, you will use a method called fast prototyping . This consists of writing the smallest portion of the specification you can implement that will still do something. In our case, you will cut the four functions down to a one-function calculator. Once you get this small part working, you can build the rest of the functions onto this stable foundation. Also, the prototype gives the boss something to look at and play around with so he has a good idea of the direction the project is taking. Good communication is the key to good programming, and the more you can show someone, the better. The code for the first version of the four-function calculator is found in Example 7-1.

Example 7-1. calc1/calc.cpp
 #include <iostream> int   result;    // the result of the calculations  char  oper_char; // operator the user specified  int   value;     // value specified after the operator int main(  ) {     result = 0; // initialize the result      // Loop forever (or till we hit the break statement)      while (true) {         std::cout << "Result: " << result << '\n';         std::cout << "Enter operator and number: ";         std::cin >> oper_char >> value;         if (oper_char = '+') {             result += value;         } else {             std::cout << "Unknown operator " << oper_char << '\n';         }     }     return (0); } 

The program begins by initializing the variable result to zero. The main body of the program is a loop starting with:

 while (true) { 

This will loop until a break statement is reached. The code:

 std::cout << "Enter operator and number: ";      std::cin >> oper_char >> value; 

asks the user for an operator and number. These are parsed and stored in the variables oper_char and value . (The full set of I/O operations such as << and >> are described in Chapter 16.) Finally, you start checking the operators. If the operator is a plus (+), you perform an addition using the line:

 if (oper_char = '+') {          result += value; 

So far you recognize only the plus operator. As soon as this works, you will add more operators by adding more if statements.

Finally, if an illegal operator is entered, the line:

 } else {           std::cout << "Unknown operator " << oper_char << '\n';      } 

writes an error message telling the user he made a mistake.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

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