C++ Notes: Program Structure
Using Borland/Inprise C++Builder 4/5
We're going to use JBuilder to build a console based program,
not a GUI (Graphical User Interface) program.
We won't be using the default form windows that appear when you first run C++Builder.
- Start C++Builder.
- Ignore the windows that C++Builder starts with.
- Select the "File/New..." menu item.
- Choose "Console Wizard" from the window that appears.
- The dialog box varies, depending on the version, but you will
select "Console" or "Console Application",
"Execution Type" (".EXE" should be selected), and you should not
include VCL. Click "Finish".
- You will see a sample starting C++ main console program.
Ignore it and replace it with your program.
- Compile and Run your program the the "Run/Run" menu item or F9.
- Stepping thru your program can be done with F8 (menu item "Run/Step Over").
- You can stop your program with CTRL-C.
- Save your "project" (.bpr, .cpp files) somewhere (Drive D in the lab).
|
Header Files
| #include <iostream> | Stream I/O. Defines cout and cin streams, and endl,
fixed, and showpoint manipulators. |
| #include <iomanip> | More I/O manipulaters: setw(w) and setprecision(p). |
| #include <fstream> | File I/O. |
| #include <string> | Defines the string type and string functions. |
| #include <cstring> | Defines C-style string (array of chars) functions. |
General Structure
A common structure for relatively simple C++ programs that are contained in one file is:
| General Rule | Example |
- Comments describing program, author, ...
- Include statements.
- Using statement.
- Global declarations (consts, types, variables, ...).
- Function headers (declarations).
- Main function body.
- Function bodies.
Some older compilers may not be in complete compliance with the latest C++ standard.
Some features that are commonly lacking and how to solve the problem are:
| Standard | Pre-Standard |
| #include <xxx> | You may have to add a ".h" to the name of a header
file. Eg, "#include <iostream.h>" instead
of the standard "#include <iostream>". |
| #include <string> | This header file and the string type may not
be defined. Use the older C-style strings and the
functions in <cstring.h>, or find a definition
for the string type and functions. |
| using namespace std; | Namespaces are not in older versions of C++. Omit this statement. |
| bool | bool type is not in some older versions of C++. Use int, 1 as true, 0 as false. |
|
//--- Print Ulam Sequence....
#include <iostream>
using namespace std;
int main() {
int n; // Ulam sequence start
while (cin >> n) {
cout << "n = " << n << endl;
while (n > 1) {
if (n%2 == 0) { // if even
n = n /2;
}else{ // if odd
n = 3*n + 1;
}
cout << "n = " << n << endl;
}
}
return 0;
}
|
|