Ubuntu You will develop your course projects in C++ under Ubuntu Linux. If your home computer or laptop is running under Windows, an easy and painless way of installing Ubuntu is Wubi: http://www.ubuntu.com/download/desktop/windowsinstaller The Wubi installer will put the latest version of Ubuntu onto your computer. Ubuntu Wubi does not require its own partition on your hard drive but simulates a file system within one large file. As a consequence, file operations are slightly less efficient than in an actual Ubuntu installation, but that difference does not matter for our purposes. When your computer starts, you will see a boot menu that allows you to choose between Windows and Ubuntu. Wubi can easily be uninstalled, in which case the boot menu will no longer show up. 1 2 Ubuntu C++ Overview Another possibility is to download a Ubuntu CD image (.iso file): http://www.ubuntu.com/download and then run it as a virtual machine using the VMWare Player: http://www.vmware.com/products/player/ In either case, also download the g++ compiler from your Ubuntu terminal by typing: $ sudo apt-get install g++ History and major features of C++ Input and output Preprocessor directives 3 4 History of C++ 1980: C-with-classes developed by Bjarne Stroustrup 1983: C-with-classes redesigned and called C++ 1985: C++ compilers made available 1989: ANSI/ISO C++ standardization starts 1998: ANSI/ISO C++ standard approved Major Features of C++ Almost upward compatible with C Not all valid C programs are valid C++ programs. Why? Because of reserved words in C++ such as class Extends C with object-oriented features Compile-time checking: strongly typed Classes with multiple inheritance No garbage collection, but semi-automatic storage reclamation 5 6 1
#include <iostream> string deptchairname, deptchairpasswd, enteredpasswd; bool passwdok; int attempts = 0; Sample C++ Program deptchairname = GetDeptChairName(); deptchairpasswd = GetDeptChairPasswd(); cout << "How are you today, " << deptchairname << "?\n"; do cout << "Please enter your password: "; cin >> enteredpasswd; attempts++; if (enteredpasswd == deptchairpasswd) cout << "Thank you!" << endl; passwdok = true; else cout << "Hey! Are you really " << deptchairname << "?\n"; cout << "Try again!\n"; passwdok = false; while (!passwdok && attempts < 3); if (passwdok) SetNewParameters(); else Shout( Warning! Illegal access! ); CallCampusPolice(); 7 Some standard functions for input and output are provided by the iostream library. The iostream library is part of the standard library. Input from the terminal (standard input) is tied to the iostream object cin. Output to the terminal (standard output) is tied to the iostream object cout. Error and warning messages can be sent to the user via the iostream object cerr (standard error). 8 Use the output operator (<<) to direct a value to standard output. Successive use of << allows concatenation. Examples: cout << Hi there!\n ; cout << I have << 3 + 5 << classes today. ; cout << goodbye! << endl; (new line & flush) Use the input operator (>>) to read a value from standard input. Standard input is read word by word (words are separated by spaces, tabs, or newlines). Successive use of >> allows reading multiple words into separate variables. Examples: cin >> name; cin >> namea >> nameb; 9 10 How can we read an unknown number of input values? while (cin >> word) cout << word read is: << word << \n ; cout << OK, that s all.\n ; The previous program will work well if we use a file instead of the console (keyboard) as standard input. In Linux, we can do this using the < symbol. Let us say that we have created a text file input.txt (e.g., by using gedit) in the current directory. It contains the following text: This is just a stupid test. Let us further say that we stored our program in a file named test.c in the same directory. 11 12 2
We can now compile our program using the g++ compiler into an executable file named test : $ g++ test.c o test The generated code can be executed using the following command: $./test If we would like to use the content of our file input.txt as standard input for this program, we can type the following command: $./test < input.txt We will then see the following output in our terminal: Word read is: This Word read is: is Word read is: just Word read is: a Word read is: stupid Word read is: test. OK, that s all. 13 14 If we want to redirect the standard output to a file, say output.txt, we can use the > symbol: $./test < input.txt > output.txt We can read the contents of the generated file by simply typing: $ less output.txt We will then see that the file contains the output that we previously saw printed in the terminal window. (By the way, press Q to get the prompt back.) If you use keyboard input for your program, it will never terminate but instead wait for additional input. Use the getline command to read an entire line from cin, and put it into a stringstream object that can be read word by word just like cin. Using stringstream objects requires the inclusion of the sstream header file: #include <sstream> 15 16 #include <iostream> #include <sstream> string userinput, word; getline(cin, userinput); stringstream mystream(userinput); while (mystream >> word) cout << "word read is: " << word << "\n"; cout << "OK, that s all.\n"; 17 By the way, you are not limited to strings when using cin and cout, but you can use other types such as integers. However, if your program expects to read an integer and receives a string, the read operation will fail. If your program always uses file input and output, it is better to use fstream objects instead of cin and cout. 18 3
#include <iostream> #include <fstream> ofstream outfile( out_file.txt ); ifstream infile( in_file.txt ); if (!infile) cerr << error: unable to open input file ; return 1; File if (!outfile) cerr << error: unable to open output file ; return 2; while (infile >> word) outfile << word << _ ; 19 Preprocessor directives are specified by placing a pound sign (#) in the very first column of a line in our program. For example, header files are made part of our program by the preprocessor include directive. The preprocessor replaces the #include directive with the contents of the named file. There are two possible forms: #include <standard_file.h> #include my_file.h 20 If the file name is enclosed in angle brackets (<, >), the file is presumed to be a standard header file. Therefore, the preprocessor will search for the file in a predefined set of locations. If the file name is enclosed by a pair of quotation marks, the file is presumed to be a user-supplied header file. Therefore, the search for the file begins in the directory in which the including file is located (project directory). The included file may itself contain an #include directive (nesting). This can lead to the same header file being included multiple times in a single source file. Conditional directives guard against the multiple processing of a header file. Example: #ifndef SHOUT_H #define SHOUT_H /* shout.h definitions go here */ #endif 21 22 The #ifdef, #ifndef, and #endif directives are most frequently used to conditionally include program code depending on whether a preprocessor constant is defined. This can be useful, for example, for debugging: #ifdef DEBUG cout << Beginning execution of main()\n ; #endif while (cin >> word) cout << word read is: << word << \n ; cout << OK, that s all. ; 23 24 4
are an important aid to human readers of our programs. need to be updated as the software develops. Do not obscure your code by mixing it with too many comments. Place a comment block above the code that it is explaining. do not increase the size of the executable file. 25 In C++, there are two different comment delimiters: the comment pair (/*, */), the double slash (//). The comment pair is identical to the one used in C: The sequence /* indicates the beginning of a comment. The compiler treats all text between a /* and the following */ as a comment. A comment pair can be multiple lines long and can be placed wherever a tab, space, or newline is permitted. Comment pairs do not nest. 26 The double slash serves to delimit a single-line comment: Everything on the program line to the right of the delimiter is treated as a comment and ignored by the compiler. A typical program contains both types of comments. In general, use comment pairs to explain the capabilities of a class and the double slash to explain a single operation. 27 5