1-Getting Started

来源:互联网 发布:java自学书籍知乎 编辑:程序博客网 时间:2024/04/29 06:04

Please indicate the source: http://blog.csdn.net/gaoxiangnumber1
Welcome to my github: https://github.com/gaoxiangnumber1

  • In this chapter, we’ll write a program to solve a simple problem for a bookstore. Our store keeps a file of transactions, each of which records the sale of one or more copies of a single book. Each transaction contains three data elements: 0-201-70353-X 4 24.99
  • The first element is an ISBN (International Standard Book Number, a unique book identifier), the second is the number of copies sold, and the last is the price at which each of these copies was sold.

1.1. Writing a Simple C++ Program

  • Every C++ program contains one or more functions, one of which must be named main. The operating system runs a C++ program by calling main.
  • A function definition has four elements: a return type, a function name, a (possibly empty) parameter list enclosed in parentheses, and a function body.
  • The main function is required to have a return type of int, which is a built-in type.
  • The final part of a function definition, the function body, is a block of statements starting with an open curly brace and ending with a close curly.
  • A return terminates a function. A return can send a value back to the function’s caller. When a return statement includes a value, the value returned must have a type that is compatible with the return type of the function.

Key Concept: Types

  • A type defines both the contents of a data element and the operations that are possible on those data. The data our programs manipulate are stored in variables and every variable has a type. When the type of a variable named v is T, we often say that “v has type T” or, interchangeably, that “v is a T.”

1.1.1. Compiling and Executing Our Program

Program Source File Naming Convention

  • Program files are referred to as a source files. On most systems, the name of a source file ends with a suffix, which is a period followed by one or more characters. The suffix tells the system that the file is a C++ program. Different compilers use different suffix conventions; the most common include .cc, .cxx, .cpp, .cp, and .C.

Running the Compiler from the Command Line

  • If we are using a command-line interface, we will typically compile a program in a console window. Assuming that our main program is in a file named prog1.cc, we might compile it by using a command such as
    CC prog1.cc
    where CC names the compiler and is the system prompt. The compiler generates an executable file.
  • UNIX compilers tend to put their executables in files named a.out. To run an executable on UNIX, we use the full file name, including the file extension:
    a.out
  • If we need to specify the file’s location, we’d use a “.” followed by a forward slash to indicate that our executable is in the current directory:
    ./a.out
  • The value returned from main is accessed in a system-dependent manner. On UNIX, after executing the program, we obtain the status by writing
    echo?

Running the GNU or Microsoft Compilers

  • The command used to run the C++ compiler varies across compilers and operating systems. The most common compilers are the GNU compiler and the Microsoft Visual Studio compilers. By default, the command to run the GNU compiler is g++:
    g++ -o prog1 prog1.cc
  • Here $ is the system prompt. The -o prog1 is an argument to the compiler and names the file in which to put the executable file. This command generates an executable file named prog1. On UNIX, executable files have no suffix. If the -o prog1 is omitted, the compiler generates an executable named a.out on UNIX systems. Depending on the release of the GNU compiler you are using, you may need to specify -std=c++0x to turn on C++11 support.
  • Compilers usually include options to generate warnings about problematic constructs. It is usually a good idea to use these options. Our preference is to use -Wall with the GNU compiler.

Exercises Section 1.1.1

Exercise1.1:

Review the documentation for your compiler and determine what file naming convention it uses. Compile and run the main program from page 2.

Exercise 1.2

Change the program to return -1. A return value of -1 is often treated as an indicator that the program failed. Recompile and rerun your program to see how your system treats a failure indicator from main.

  • Why 255: http://www.tldp.org/LDP/abs/html/exitcodes.html

1.2 A First Look at Input/Output

  • Fundamental to the iostream library are two types named istream and ostream, which represent input and output streams, respectively. A stream is a sequence of characters read from or written to an IO device.

Standard Input and Output Objects

  • The library defines four IO objects.
    1. Standard Input: use an object of type istream named cin (pronounced see-in).
    2. Standard Output: use an ostream object named cout (pronounced see-out ).
    3. Standard Error: use an ostream object named cerr (pronounced see-err) for warning and error messages.
    4. clog (pronounced and see-log) for general information about the execution of the program.

A Program That Uses the IO Library

#include <iostream>int main(){    std::cout << "Enter two numbers:" << std::endl;    int v1 = 0, v2 = 0;    std::cin >> v1 >> v2;    std::cout << "The sum of " << v1 << " and " << v2              << " is " << v1 + v2 << std::endl;    return 0;}
  • The first line tells the compiler that we want to use the iostream library. The name inside angle brackets (iostream in this case) refers to a header. Every program that uses a library facility must include its associated header. The #include directive must be written on a single line—the name of the header and the #include must appear on the same line.
  • In general, #include directives must appear outside any function. We put all the #include directives for a program at the beginning of the source file.

Writing to a Stream

  • The first statement in the body of main executes an expression. In C++ an expression yields a result and is composed of one or more operands and an operator.
  • The << operator takes two operands: The left-hand operand must be an ostream object; the right-hand operand is a value to print. The operator writes the given value on the given ostream. The result of the output operator is its left-hand operand.
  • Our output statement uses the << operator twice. Because the operator returns its left-hand operand, the result of the first operator becomes the left-hand operand of the second. So we can chain together output requests, and our expression is equivalent to
    (std::cout << “Enter two numbers:”) << std::endl;
  • endl is a manipulator. Writing endl has the effect of ending the current line and flushing the buffer associated with that device. Flushing the buffer ensures that all the output the program has generated so far is actually written to the output stream, rather than sitting in memory waiting to be written.
  • Programmers often add print statements during debugging. Such statements should always flush the stream. Otherwise, if the program crashes, output may be left in the buffer, leading to incorrect inferences about where the program crashed.

Using Names from the Standard Library

  • The prefix std:: indicates the namespace named std which indicates the standard library. Namespaces allow us to avoid inadvertent collisions between the names we define and uses of those same names inside a library.
  • When we use a name from the library, we must uses the scope operator (::) to say explicitly that we want to use the name from which namespace.

Reading from a Stream

  • When we initialize a variable, we give it the indicated value at the same time as the variable is created.
  • The input operator >> takes an istream as its left-hand operand and an object as its right-hand operand. It reads data from the given istream and stores what was read in the given object. The input operator returns its left-hand operand as its result, so we can combine a sequence of input requests into a single statement.

Completing the Program

  • std::cout << “The sum of ” << v1 << ” and ” << v2 << ” is ” << v1 + v2 << std::endl; This statement prints each of its operands on the standard output. What is interesting is that the operands are not all the same kinds of values. The library defines versions of the input and output operators that handle operands of each of these differing types.

Exercises Section 1.2

Exercise 1.3

Write a program to print Hello, World on the standard output.

#include <iostream>int main(){    std::cout << "Hello, World" << std::endl;    return 0;}

Exercise 1.4

Our program used the addition operator, +, to add two numbers. Write a program that uses the multiplication operator, *, to print the product instead.

#include <iostream>int main(){    std::cout << "Enter two numbers:" << std::endl;    int v1 = 0, v2 = 0;    std::cin >> v1 >> v2;    std::cout << "The product of " << v1 << " and " << v2 << " is " << v1 * v2 << std::endl;    return 0;}

Exercise 1.5:

We wrote the output in one large statement. Rewrite the program to use a separate statement to print each operand.

#include <iostream>int main(){    std::cout << "Enter two numbers:" << std::endl;    int v1 = 0, v2 = 0;    std::cin >> v1 >> v2;    std::cout << "The product of ";    std::cout << v1;    std::cout << " and ";    std::cout << v2;    std::cout << " is ";    std::cout << v1 * v2;    std::cout << std::endl;    return 0;}

Exercise 1.6:

Explain whether the following program fragment is legal.

std::cout   << "The sum of " << v1;<< " and " << v2;<< " is " << v1 + v2 << std::endl;

If the program is legal, what does it do? If the program is not legal, why not? How would you fix it?

  • Illegal: 1-6.cpp|9|error: expected primary-expression before ‘<<’ token|.
  • Fix it: remove the spare semicolons.

1.3. A Word about Comments

Kinds of Comments in C++

  • There are two kinds of comments in C++: single-line and paired.
    1. A single-line comment starts with a double slash (//) and ends with a newline. Everything to the right of the slashes on the current line is ignored by the compiler. This kind comment can contain any text, including additional double slashes.
    2. A paired comment uses two delimiters (/* and /). Such comments begin with a / and end with the next /. These comments can include anything that is not a /, including newlines. This kind comment can be placed anywhere a tab, space, or newline is permitted.
  • Comment pairs can span multiple lines of a program. When a comment pair does span multiple lines, we usually begin each line in the comment with an asterisk(*), thus indicating that the entire range is part of a multiline comment.
#include <iostream>/** Simple main function:* Read two numbers and write their sum*/int main(){    // prompt user to enter two numbers    std::cout << "Enter two numbers:" << std::endl;    int v1 = 0, v2 = 0; // variables to hold the input we read    std::cin >> v1 >> v2; // read input    std::cout << "The sum of " << v1 << " and " << v2 << " is " << v1 + v2 << std::endl;    return 0;}

Comment Pairs Do Not Nest

  • A comment that begins with /* ends with the next */, so one comment pair cannot appear inside another.
/** comment pairs /* */ cannot nest.* ''cannot nest'' is considered source code,* as is the rest of the program*/int main(){    return 0;}
  • The best way to comment a block of code is to insert single-line comments at the beginning of each line in the section we want to ignore:
// /*// * everything inside a single-line comment is ignored// * including nested comment pairs// */

Exercises Section 1.3**

Exercise 1.7:

Compile a program that has incorrectly nested comments.

/** comment pairs /* */ cannot nest.* ''cannot nest'' is considered source code,* as is the rest of the program*/int main(){    return 0;}

Exercise 1.8:

Indicate which, if any, of the following output statements are legal:

std::cout << "/*";std::cout << "*/";std::cout << /* "*/" */;std::cout << /* "*/" /* "/*" */;

After you’ve predicted what will happen, test your answers by compiling a program with each of these statements. Correct any errors you encounter.

  • Correct: Add a quote to the third cout.

1.4. Flow of Control

1.4.1. The while Statement

#include <iostream>int main(){    int sum = 0, val = 1;    // keep executing the while as long as val is less than or equal to 10    while (val <= 10)    {        sum += val;  // assigns sum + val to sum        ++val;  // add 1 to val    }    std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;    return 0;}
  • A while has the form
while (condition)    statement
  • A while executes by alternately testing the condition and executing the associated statement until the condition is false. A condition is an expression that yields a result that is either true or false.
  • A block is a sequence of zero or more statements enclosed by curly braces. A block is a statement and may be used wherever a statement is required.
  • The += operator adds its right-hand operand to its left-hand operand and stores the result in the left-hand operand. It has the same effect as writing an addition and an assignment:
    sum = sum + val; // assign sum + val to sum

Exercises Section 1.4.1

Exercise 1.9:

Write a program that uses a while to sum the numbers from 50 to 100.

#include <iostream>int main(){    int num = 50, sum = 0;    while(num <= 100)    {        sum += num;        ++num;    }    std::cout << "The sum from 50 to 100 is " << sum << std::endl;    return 0;}

Exercise 1.10:

In addition to the ++ operator that adds 1 to its operand, there is a decrement operator (–) that subtracts 1. Use the decrement operator to write a while that prints the numbers from ten down to zero.

#include <iostream>int main(){    int num = 10;    while(num >= 0)    {        std::cout << num << std::endl;        --num;    }    return 0;}

Exercise 1.11:

Write a program that prompts the user for two integers. Print each number in the range specified by those two integers.

#include <iostream>using std::cout;using std::cin;using std::endl;int main(){    int small = 0, big = 0;    cout << "Please input 2 integers: ";    cin >> small >> big;    if(small > big)    {        int temp = small;        small = big;        big = small;    }    // Print integers in the range [num1, num2]:    while(small <= big)    {        cout << small << endl;        ++small;    }    return 0;}

1.4.2. The for Statement

#include <iostream>int main(){    int sum = 0;    // sum values from 1 through 10 inclusive    for (int val = 1; val <= 10; ++val)        sum += val; // equivalent to sum = sum + val    std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;    return 0;}
  • Each for statement has two parts: a header and a body. The header controls how often the body is executed. The header itself consists of three parts: an init-statement, a condition , and an expression.
  • The overall execution flow of this for is:
    1. Create val and initialize it to 1.
    2. Test whether val is less than or equal to 10. If the test succeeds, execute the for body. If the test fails, exit the loop and continue execution with the first statement following the for body.
    3. Increment val.
    4. Repeat the test in step 2, continuing with the remaining steps as long as the condition is true.

Exercises Section 1.4.2

Exercise 1.12:

What does the following for loop do? What is the final value of sum?

int sum = 0;for (int i = -100; i <= 100; ++i)    sum += i;
  • Calculate the sum form -100 to 100, the result is 0.

Exercise 1.13:

Rewrite the exercises from § 1.4.1 (p. 13) using for loops.

#include <iostream>using std::cin;using std::cout;using std::endl;int main(){    /*    * Exercise 1.9: Write a program that uses a while    * to sum the numbers from 50 to 100.    */    cout << "Exercise 1.9\n";    int sum = 0;    for(int num = 50; num <= 100; ++num)    {        sum += num;    }    cout << "The sum from 50 to 100 is " << sum << endl;    /*    * Exercise 1.10: Use the decrement operator to write a while    * that prints the numbers from ten down to zero.    */    cout << "Exercise 1.10\n";    for(int num = 10; num >= 0; --num)    {        cout << num << endl;    }    /*    * Exercise 1.11: Write a program that prompts the user for two integers.    * Print each number in the range specified by those two integers.    */    cout << "Exercise 1.11\n";    int num1 = 0, num2 = 0;    cout << "Please input 2 integers: ";    cin >> num1 >> num2;    // We make num1 <= num2    if(num1 > num2)    {        int temp = num1;        num1 = num2;        num2 = temp;    }    // Print integers in the range [num1, num2]:    for(; num1 <= num2; ++num1)    {        cout << num1 << endl;    }    return 0;}

Exercise 1.14:

Compare and contrast the loops that used a for with those using a while. Are there advantages or disadvantages to using either form?

Ad/Disad for while Advantages 1.Locality, the variable in the scope of the loop. 2.Pattern happens so often: using a variable in a condition and incrementing that variable in the body. 1.Clear when there is only one static condition. 2.Readable when the global variables incremented in the body. Disadvantages while’s advantages for’s advantages

Exercise 1.15:

Write programs that contain the common errors discussed in the box on page 16. Familiarize yourself with the messages the compiler generates.

  • Self-training

1.4.3. Reading an Unknown Number of Inputs

#include <iostream>int main(){    int sum = 0, value = 0;    // read until end-of-file, calculating a running total of all values read    while (std::cin >> value)        sum += value; // equivalent to sum = sum + value    std::cout << "Sum is: " << sum << std::endl;    return 0;}
  • while(std::cin >> value)
    The expression std::cin >> value reads the next number from the standard input and stores that number in value. The input operator (§ 1.2, p. 8) returns its left operand, which in this case is std::cin. This condition tests std::cin. When we use an istream as a condition, the effect is to test the state of the stream. If the stream is valid, then the test succeeds. An istream becomes invalid when we hit end-of-file(Ctrl+d on Linux) or encounter an invalid input, such as reading a value that is not an integer. An istream that is in an invalid state will cause the condition to yield false.

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.

#include <iostream>using std::cin;using std::cout;using std::endl;int main(){    int sum = 0;    for(int value = 0; cin >> value;)    {        sum += value;    }    cout << "The sum is " << sum << endl;    return 0;}

1.4.4. The if Statement

#include <iostream>int main(){    // currVal is the number we're counting; we'll read new values into val    int currVal = 0, val = 0;    // read first number and ensure that we have data to process    if (std::cin >> currVal)    {        int cnt = 1; // store the count for the current value we're processing        while (std::cin >> val)   // read the remaining numbers        {            if (val == currVal) // if the values are the same                ++cnt; // add 1 to cnt            else   // otherwise, print the count for the previous value            {                std::cout << currVal << " occurs " << cnt << " times" << std::endl;                currVal = val; // remember the new value                cnt = 1; // reset the counter            }        } // while loop ends here        // remember to print the count for the last value in the file        std::cout << currVal << " occurs " << cnt << " times" << std::endl;    } // outermost if statement ends here    return 0;}
  • C++ uses = for assignment and == for equality. Both operators can appear inside a condition. It is a common mistake to write = when you mean == inside a condition.

Exercises Section 1.4.4

Exercise 1.17:

What happens in the program presented in this section if the input values are all equal? What if there are no duplicated values?

  • If the input values are all equal, it will print a line which shows the count of the number you input.
  • If there are no duplicated values, when different values input, a new line will be printed if you click Enter.

Exercise 1.18:

Compile and run the program from this section giving it only equal values as input. Run it again giving it values in which no number is repeated.

Exercise 1.19:

Revise the program you wrote for the exercises in § 1.4.1 (p. 13) that printed a range of numbers so that it handles input in which the first number is smaller than the second.

#include <iostream>using std::cout;using std::cin;using std::endl;int main(){    int small = 0, big = 0;    cout << "Please input 2 integers: ";    cin >> small >> big;    if(small > big)    {        int temp = small;        small = big;        big = small;    }    // Print integers in the range [num1, num2]:    while(small <= big)    {        cout << small << endl;        ++small;    }    return 0;}

Classes

  • A class defines a type along with a collection of operations that are related to that type.
  • To use a class we need to know three things:
    1. What is its name?
    2. Where is it defined?
    3. What operations does it support?
  • For our bookstore problem, we assume that the class is named Sales_item and it is defined in Sales_item.h.
  • Conventionally, header file names are derived from the name of a class defined in that header. Header files usually have a suffix of .h, but some programmers use .H, .hpp, or .hxx. The standard library headers typically have no suffix at all.

1.5.1. The Sales_item Class

  • The purpose of the Sales_item class is to represent the total revenue, number of copies sold, and average sales price for a book.
  • Every class defines a type. The type name is the same as the name of the class. When we write
    Sales_item item;
    item is an object of type Sales_item.

Reading and Writing Sales_items

#include <iostream>#include "Sales_item.h"int main(){    Sales_item book;    // read ISBN, number of copies sold, and sales price    std::cin >> book;    // write ISBN, number of copies sold, total revenue, and average price    std::cout << book << std::endl;    return 0;}
  • If the input to this program is
    0-201-70353-X 4 24.99
    then the output will be
    0-201-70353-X 4 99.96 24.99
  • Our input says that we sold four copies of the book at 24.99 each, and the output indicates that the total sold was four, the total revenue was 99.96, and the average price per book was 24.99.
  • Headers from the standard library are enclosed in angle brackets (< >). Those that are not part of the library are enclosed in double quotes (” “).

Adding Sales_items

#include <iostream>#include "Sales_item.h"int main(){    Sales_item item1, item2;    std::cin >> item1 >> item2; // read a pair of transactions    std::cout << item1 + item2 << std::endl; // print their sum    return 0;}
  • If we give this program the following input
    0-201-78345-X 3 20.00
    0-201-78345-X 2 25.00
    our output is
    0-201-78345-X 5 110 22

Using File Redirection

  • Most operating systems support file redirection, which lets us associate a named file with the standard input and the standard output:
    addItems outfile
  • Assuming $ is the system prompt and our addition program has been compiled into an executable file named addItems, this command will read transactions from a file named infile and write its output to a file named outfile in the current directory.

Exercises Section 1.5.1

Exercise 1.20:

http://www.informit.com/title/032174113 contains a copy of Sales_item.h in the Chapter 1 code directory. Copy that file to your working directory. Use it to write a program that reads a set of book sales transactions, writing each transaction to the standard output.

#include "sales_item.h"using std::cin;using std::cout;using std::endl;int main(){    for(SalesItem item; cin >> item; cout << item << endl);    return 0;}

Exercise 1.21:

Write a program that reads two Sales_item objects that have the same ISBN and produces their sum.

#include "sales_item.h"using std::cin;using std::cout;using std::cerr;using std::endl;int main(){    Sales_item item1, item2;    cin >> item1 >> item2;    if(item1.isbn() == item2.isbn())    {        cout << item1 + item2 << endl;    }    else    {        cerr << "Input error: different ISBN.\n";    }}

Exercise 1.22:

Write a program that reads several transactions for the same ISBN. Write the sum of all the transactions that were read.

#include "sales_item.h"using std::cin;using std::cout;using std::cerr;using std::endl;int main(){    Sales_item total;    if(cin >> total)    {        Sales_item trans;        while (cin >> trans)        {            if (total.isbn() == trans.isbn())            {                total += trans;            }            else            {                cout << total << endl;                total = trans;            }        }        cout << total << endl;    }    else    {        cerr << "Input Error" << endl;        return -1;    }    return 0;}

1.5.2. A First Look at Member Functions

  • Our program that adds two Sales_items should check whether the objects have the same ISBN.
#include <iostream>#include "Sales_item.h"int main(){    Sales_item item1, item2;    std::cin >> item1 >> item2;    // first check that item1 and item2 represent the same book    if (item1.isbn() == item2.isbn())    {        std::cout << item1 + item2 << std::endl;        return 0; // indicate success    }    else    {        std::cerr << "Data must refer to same ISBN" << std::endl;        return -1; // indicate failure    }}

What Is a Member Function?

  • item1.isbn() == item2.isbn()
    calls a member function named isbn. A member function is a function that is defined as part of a class. Member functions are sometimes referred to as methods. We call a member function on behalf of an object. The first part of the left-hand operand of the equality expression
    item1.isbn
    uses the dot operator (the “.” operator) to say that we want “the isbn member of the object named item1.” The dot operator applies only to objects of class type. The left-hand operand must be an object of class type, and the right-hand operand must name a member of that type. The result of the dot operator is the member named by the right-hand operand.
  • We call a function using the call operator (the () operator). The call operator is a pair of parentheses that enclose a (possibly empty) list of arguments.

Exercises Section 1.5.2

Exercise 1.23:

Write a program that reads several transactions and counts how many transactions occur for each ISBN.

#include "Sales_item.h"using std::cin;using std::cout;using std::endl;int main(){    Sales_item current_item, input_item;    if (cin >> current_item)    {        int cnt = 1;        while (cin >> input_item)        {            if (input_item.isbn() == current_item.isbn())            {                ++cnt;            }            else            {                cout << current_item << " occurs " << cnt << " times " << endl;                current_item = input_item;                cnt = 1;            }        }        cout << current_item << " occurs " << cnt << " times " << endl;    }    return 0;}

Exercise 1.24:

Test the previous program by giving multiple transactions representing multiple ISBNs. The records for each ISBN should be grouped together.

1.6. The Bookstore Program

  • We need to read a file of sales transactions and produce a report that shows, for each book, the total number of copies sold, the total revenue, and the average sales price. We assume that all the transactions for each ISBN are grouped together in the input.
  • Our program will combine the data for each ISBN in a variable named total. We’ll use a second variable named trans to hold each transaction we read. If trans and total refer to the same ISBN, we’ll update total. Otherwise we’ll print total and reset it using the transaction we just read:
#include <iostream>#include "Sales_item.h"int main(){    Sales_item total; // variable to hold data for the next transaction    // read the first transaction and ensure that there are data to process    if (std::cin >> total)    {        Sales_item trans; // variable to hold the running sum        // read and process the remaining transactions        while (std::cin >> trans)        {            // if we're still processing the same book            if (total.isbn() == trans.isbn())            {                total += trans; // update the running total            }            else            {                // print results for the previous book                std::cout << total << std::endl;                total = trans; // total now refers to the next book            }        }        std::cout << total << std::endl; // print the last transaction    }    else    {        // no input! warn the user        std::cerr << "No data?!" << std::endl;        return -1; // indicate failure    }    return 0;}

Exercises Section 1.6

Exercise 1.25:

Using the Sales_item.h header from the Web site, compile and execute the bookstore program presented in this section.

  • It is the same as Exercise 1.22.

Chapter Summary
Please indicate the source: http://blog.csdn.net/gaoxiangnumber1
Welcome to my github: https://github.com/gaoxiangnumber1

0 0