ENTERING AN END-OF-FILE FROM THE KEYBOARD
When we enter input to a program from the keyboard, different operating systems use different conventions to allow us to indicate end-of-file. On Windows systems we enter an end-of-file by typing a control-z—hold down the Ctrl key and press z— followed by hitting either the Enter or Return key. On UNIX systems, including on Mac OS X machines, end-of-file is usually control-d.
COMPILATION REVISITED
Part of the compiler’s job is to look for errors in the program text. A compiler cannot detect whether a program does what its author intends, but it can detect errors in the form of the program. The following are the most common kinds of errors a compiler will detect.
Syntax errors: The programmer has made a grammatical error in the C++(www.cppentry.com) language. The following programillustrates common syntax errors; each comment describes the error on the following line:
-
- int main ( {
-
- std::cout << "Read each file." << std::endl:
-
- std::cout << Update master. << std::endl;
-
- std::cout << "Write new master." std::endl;
-
- return 0
- }
Type errors: Each itemof data in C++(www.cppentry.com) has an associated type. The value 10, for example, has a type of int (or, more colloquially, “is an int”). The word "hello", including the double quotation marks, is a string literal. One example of a type error is passing a string literal to a function that expects an int argument.
Declaration errors: Every name used in a C++(www.cppentry.com) program must be declared before it is used. Failure to declare a name usually results in an error message. The two most common declaration errors are forgetting to use std:: for a name from the library and misspelling the name of an identifier:
- #include <iostream>
- int main()
- {
- int v1 = 0, v2 = 0;
- std::cin >> v >> v2;
-
- cout << v1 + v2 << std::endl;
- return 0;
- }
Error messages usually contain a line number and a brief description of what the compiler believes we have done wrong. It is a good practice to correct errors in the sequence they are reported. Often a single error can have a cascading effect and cause a compiler to report more errors than actually are present. It is also a good idea to recompile the code after each fix—or after making at most a small number of obvious fixes. This cycle is known as edit-compile-debug.
EXERCISES SECTION 1.4.3
Exercise 1.16: Write your own version of a program that prints the sum of a set of integers read from cin.