Chapter 1. Getting Started

来源:互联网 发布:知乎风油精帖子链接 编辑:程序博客网 时间:2024/04/29 17:25

Section 1.1. Writing a Simple C++ Program
    The operating system uses the value returned by [main] to determine whether the program successded or failed. A return value of 0 indicates sucess.
   
    The [main] function is the only function that the operating system explicitly calls(显式调用).

Exercises Section 1.1.1
    1.1: Review the documentation for your compiler and determine what file naming convention it uses. Compile and run the [main] program from page 2.
    Answer:
        for Visual Studio 2013, the source files are named as [*.cpp] or [*.c], the [*.c] is for C and C++ both, the [*.cpp] is for C++ only.
        the [main] program from page 2 do nothing
       
    1.2: Change the program to return -1, Areturn value of -1 is often treated as an indicator that the program failed. However, systems vary(系统的表现各不相同) as to how (or even whether) they report a failure from main. Recompile and rerun your program to see how your system treats a failure indicator from [main].
    Answer:
        the Visual Studio 2013 do nothing with the return value -1, just like return a value that is 0.
       
Section 1.2. A First Look at Input/Output
    IO is provided by the [standard library](标准库),
   
    the types named [istream] and [ostream] represent input and output streams. A stream is a sequence of characters intended to be read from or written to an IO device of some kind. The term(术语) is intended to suggest that the characters are generated, or consumed, sequentially over time(随着时间连续的生成或被消耗).
    The library defines 4 IO objects.
        for what?       type        object named what?      meaning
        input           istream     cin                     standard input
        output          ostream     cout                    standard output
        output          ostream     cerr                    standard error(used to generate warning and error messages to users of program)
        output          ostream     clog                    (used for general information about the execution of the program)
       
    the value returned by an output operation is the output stream it self.for example
        std::cout << "Enter two numbers:"
    this statement returns its left operand(左操作数), actually is the [std::out] itself.
    so we can do this:
        std::cout << "Enter two numbers, " << "You fucking retard:" << std::endl;
   
    [endl]is a special value, called a [manipulator](操纵符), that when written to an output stream has the effect or writing a newline to the output and blushing the [buffer] associated with that device. By flushing the buffer, we ensure that the user will see the output written to the stream immediately.
    the print statements should always flush the stream. Forgetting to do so may cause output to be left in the buffer if the program crashes, leading to incorrect inferences about where the program crashed.
   
    the prefix [std::] indicates that the names [cout] and [endl] are defined inside the [namespace] named [std], Namespaces allow programmers to avoid inadvertent collisions(无意的冲突) with the same names defined by a library.
    the [::] is named as a [scope operator](作用域操作符)
   
    spaces inside a string literal cannot be replaced by a newline.
    spaces are not allowed inside preprocessor directives.(预处理指示)
   
Exercises Section 1.2.2
    1.3: Write a program to print "Hello, World" on the standard output.
    Here is the Code:
        #include <iostream>

        int main(void)
        {
            std::cout << "Hello World" << std::endl;

            return 0;
        }
       
    1.4: Our program used the built-in addition operator, +, to generate the sum of two numbers, Write a program that uses the multiplication operator, *, to generate the product of two numbers.
    Here is the Code:
        #include <iostream>

        int main(void)
        {
            int num1, num2;
            std::cout << "Enter two numbers:" << std::endl;
            std::cin >> num1 >> num2;

            std::cout << "The multiplication answer of" << num1 << " and " << num2 << " is: " << num1*num2 << std::endl;

            return 0;
        }
       
    1.5: We wrote the output in one large statement. Rewrite the program to use a separate statement to print each operand.
    Here is the Code:
        #include <iostream>
       
        int main()
        {
            std::cout << "Enter two numbers:";
            std::cout << std::endl;

            int v1, v2;

            std::cin >> v1;
            std::cin >> v2;

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

            return 0;
        }
    1.6: Explain what the following program fragment does:
        std::cout << "The sum of " << v1;
                  << " and " << v2;
                  << " is " << v1 + v2;
                  << std::endl;
    is this code legal? If so, why? If not, why not?
    Answer:
        the above program fragment intend to print a statement on the screen just like the example:
            The sum of 7 and 9 is 16
        but this code is illegal, the above fragment is consist of 4 statements, actually they should be 1 statement like this:
            std::cout << "The sum of " << v1 << " and " << v2 << " is " << v1 + v2 << std::endl;
        or put this long statement in several lines but no semicolon among this statement, like this:
            std::cout << "The sum of " << v1
                      << " and " << v2
                      << " is " << v1 + v2
                      << std::endl;
        or write several statements to do this job, every statement should have a [std::cout], just like this
            std::cout << "The sum of " << v1;
            std::cout << " and " << v2;
            std::cout << " is " << v1 + v2;
            std::cout << std::endl;
           
Section 1.3. A Word About Comments
    Nothing important should be notes.
   
Exercises Section 1.3
    1.7: Compile a program that has incorrectly nested(嵌套) comments.
    Like this code:
        #include <iostream>

        /*
         * This program intend to print the words Emma said to Dex,
         * /*This conversation came from a book named <one day>*/
         * /*I like it very much, I also like the actress in the movie*/
         */

        int main()
        {

            std::cout << "Emma:" << std::endl;
            std::cout << "      Dex, I love you so much." << std::endl;
            std::cout << "      Just don't like you anymore." << std::endl;

            return 0;
        }
    too many [*/] confuse my compiler, it cannot find the real comment fragment, this program cannot run correctly, unless you fix this program like this:
        #include <iostream>

        // This program intend to print the word Emma said to Dex,
        // This conversation came from a book named <one day>
        // I like it very much, I also like the actress in the movie

        int main()
        {

            std::cout << "Emma:" << std::endl;
            std::cout << "      Dex, I love you so much." << std::endl;
            std::cout << "      Just don't like you anymore." << std::endl;

            return 0;
        }
    1.8: Indicate which, if any, of the following output statements, are legal.
        std::cout << "/*";
        std::cout << "*/";
        std::cout << /* "*/" */;
    After you've predicted what will happen, test your answer by compiling a program with these three statements. Correct any errors, you encounter.
    Answer:
        I hate this kind of Question, just donnot use the [/* */] method for comment in C++.
       
Section 1.4. Control Structures

    Before the Exercises Section 1.4.2, there is nothing important should be notes, the [while] and [for] loop structures of C++ is alike C.

Exercises Section 1.4.2
    1.9: What does the follwing for loop do? What is the final value of sum?
        int sum = 0;
        for(int i = -100; i <= 100; ++i)
            sum += i;
    Answer:
        this loop is intend to seeking the summation of arithmetical sequence(等差数列) [-100 -99 -98 ... 0 1 2 ... 98 99 100], obviously the answer should be 0, cause the summation of [-100 -99 -98 ... -1] is -5050, and the summation of [1 2 3 ... 100] is 5050, the sum of -5050 and 5050 is 0.
       
    1.10: Write a program that uses a for loop to sum the numbers from 50 to 100. Now rewrite the program using a while.
    The for version:
        #include <iostream>

        int main(void)
        {
            int sum = 0;
            for (int i = 50; i <= 100; ++i)
                sum += i;

            std::cout << "The answer is " << sum << std::endl;

            return 0;
        }
    The while version:
        #include <iostream>

        int main(void)
        {
            int sum = 0;
            int i = 50;

            while (i <= 100)
            {
                sum += i;
                ++i;
            }

            std::cout << "The answer is " << sum << std::endl;

            return 0;
        }
    The answer is 3825.
   
    1.11: Write a program using a while loop to print the numbers from 10 down to 0, Now rewrite the program using a for.
    The while version:
        #include <iostream>

        int main(void)
        {
            int i = 10;

            while (i >= 0)
            {
                std::cout << i << std::endl;
                --i;
            }

            return 0;
        }
    The for version:
        #include <iostream>

        int main(void)
        {
            for (int i = 10; i >= 0; --i)
                std::cout << i << std::endl;

            return 0;
        }
       
    1.12: Compare and constrast the loops you wrote in the previous two exercises. Are there advantages or disadvantages to using either form?
    Answer:
        this is not a good question, we can see the for loop form can make the program short by now, and the for loop form is more nature to do such thing as we do above, but this doesn't means the for loop is better than while loop. we'll see soon, remember, C++ preserve this two form of loop from C is not just for fun or make some programmers feel nature, it does make some sense.
       
    1.13: Compilers vary as to how easy it is to understand their diagnostics(诊断程序). Write programs that contain the common errors discussed in the box on 16, Study the messages the compiler generates so that these messages will be familiar when you encounter them while compiling more comples programs.
    Answer:
        I agree, my compiler almost fuck me every second when i study the C programing language, and it was a harrowing(令人肝肠寸断的) experience.

    Before Exercises Section 1.4.3, still nothing important.
   
Exercises Section 1.4.3
    1.14: What happens in the program presented in this section if the input values are equal?
    Answer:
        Let's take a look.
        if the numbers user input is equal, that is ,v1 == v2 == NUMBER, the if statement will make lower = v1, and upper = v2. that is , lower == upper == v1 == v2 == NUMBER,
        next, sum == 0,
        next, val = lower = NUMBER, and the test condition [val <= upper] is true, so enter the loop
        next, sum = sum + val = 0 + NUMBER == NUMBER, and the statement[++val] make val == NUMBER+1, now the first loop is over
        next, the test condition [val <= upper] is false, because now val == NUMBER+1, so ,the loop  is over.
        so, the program will print :
            Sum of NUMBER to NUMBER inclusive is NUMBER
        for example
            Sum of 99 to 99 inclusive is 99
        the result depends on the NUMBER user input.
   
    1.15: Compile and run the program from this section with two equal values as input. Compare the output to what you predicted in the previous exercise, Explain any discrepancy between what happened and what you predicted.
    Answer:
        Just like I predicted.
       
    1.16: Write a program to print the larger of two inputs supplied by the user.
    Here is the code:
        #include <iostream>

        int main(void)
        {
            int num1, num2;
            std::cout << "Please enter two number:" << std::endl;
            std::cin >> num1 >> num2;

            if (num1 > num2)
                std::cout << "the larger is " << num1 << std::endl;
            else
                std::cout << "the larger is " << num2 << std::endl;

            return 0;
        }
       
    1.17: Write a program to ask the user to enter a series of numbers, Print a message saying how many of the numbers are negative numbers.
    Here is the code:
        #include <iostream>

        int main(void)
        {
            int count = 0;      // count the negative numbers

            int temp;           // save user's input

            std::cout << "Please enter a series of numbers, the numbers should be separated by spaces or [ENTER], input any character follow a [ENTER] means input is over." << std::endl;

            while (std::cin >> temp)
            {
                if (temp < 0)
                    count++;
            }

            if (count == 0)
                std::cout << "there is no any negative number" << std::endl;
            else if (count == 1)
                std::cout << "you have entered 1 negative number" << std::endl;
            else
                std::cout << "you have entered " << count << " negative numbers" << std::endl;


            return 0;
        }

    Before Exercises Section 1.4.4, still nothing important.
   
Exercises Section 1.4.4
    1.18: Write a program that prompts the user for two numbers, and writes each number in the range specified by the two numbers to the standard output.
    Here is the code:
        #include <iostream>

        int main(void)
        {
            int num1, num2;

            std::cout << "Please enter two numbers, this program will output the range specified by them to screen soon" << std::endl;

            std::cin >> num1 >> num2;

            int lower, upper;

            if (num1 >= num2)
            {
                upper = num1;
                lower = num2;
            }
            else
            {
                upper = num2;
                lower = num1;
            }

            while (lower <= upper)
            {
                std::cout << lower << std::endl;
                ++lower;
            }

            return 0;
        }
       
    1.19: What happens if you give the numbers 1000 and 2000 to the program written for the previous exercise? Revise the program so that it never prints more that 10 numbers per line;
    Answer:
        To my code of the previous exercise, if I give the number 1000 and 2000, it will output all the number between 1000 and 2000, for each line it contain only one number. now i will add a variable named [count] to record the numbers of number output on each line. the new program will never prints more than 10 numbers per line;
    Here is the code:
        #include <iostream>

        int main(void)
        {
            int num1, num2;

            std::cout << "Please enter two numbers, this program will output the range specified by them to screen soon" << std::endl;

            std::cin >> num1 >> num2;

            int lower, upper;

            if (num1 >= num2)
            {
                upper = num1;
                lower = num2;
            }
            else
            {
                upper = num2;
                lower = num1;
            }

            int count = 0;

            while (lower <= upper)
            {
                std::cout << lower << " ";
                ++lower;
                ++count;
                // if count == 10 is true, that means this line is full, should print a ENTER
                // and for the new line, the count should be value to 0
                if (count == 10)
                {
                    std::cout << std::endl;
                    count = 0;
                }
            }

            return 0;
        }
       
    1.20: Write a program to sum the numbers in a user-specified range, omitting the if test that sets the upper and lower bounds. Predict what happens if the input is the numbers 7 and 3, in that order. Now run the program giving it the number 7 and 3, and see if the results match your expectation. If not, restudy the discussion on the for and while loop until you understand what happened.
    Answer:
        If i don't use the variables [upper] and [lower] to set the range, and if the program consider the first number from user is the lower and the second is the upper, in this situation, the program will output nothing, because the test condition make the program do not run the loop body even once.
       
Section 1.5. Introducing Classes

    In this section, you could consider the Sales_item is a struct type just like C. except that, nothing important in this section before Exercises Section 1.5.1.
   
Exercises Section 1.5.1

    1.21:The Web site (http://www.awprofessional.com/cpp_primer) contains a copy of Sales_item.h in the Chapter 1 code directory. Copy that file to your working directory. Write a program that loops through a set of book sales transactions, reading each transaction and writing that transaction to the standard output.
    Answer:
        Sadly, the website mentioned above doesn't work, but we can get the file [Sales_item.h] from some website else, just Google the filename, and then you'll find the download point.
        After download the file, you should put the file in the directory of your project.
    Here is the code:
        #include <iostream>
        #include "Sales_item.h"

        int main(void)
        {
            Sales_item item;

            std::cout << "Please enter the information of SALES" << std::endl;
            std::cout << "You should input as the format:[ISBN] [sales number] [per price]" << std::endl;
            std::cout << "For example:" << std::endl;
            std::cout << "0-201-78345-X 3 20.00" << std::endl;
            std::cout << "After each item input correctly, the program will output the information as the format like this:" << std::endl;
            std::cout << "[ISBN][sales number][total price][per price]" << std::endl;
            std::cout << "If your input's format error, the program will shutdown immedately" << std::endl;
            std::cout << "---------------------------" << std::endl;

            while (std::cin >> item)
                std::cout << item << std::endl;

            return 0;
        }
       
    1.22: Write a program that reads two Sales_item objects that have the same ISBN and produces their sum.
    Here is the code:
        #include <iostream>
        #include "Sales_item.h"

        int main(void)
        {
            Sales_item item1, item2;

            std::cout << "Please enter two record of sales as the following format:" << std::endl;
            std::cout << "[ISBN] [sales number] [per price]" << std::endl;

            std::cout << "Record #1:";
            std::cin >> item1;
            std::cout << "Record #2:";
            std::cin >> item2;

            if (item1.isbn != item2.isbn)
            {
                std::cout << "#1 and #2 is different books' Sales Record" << std::endl;

                return -1;
            }
            else
            {
                std::cout << "The summation of #1 and #2 is:" << std::endl;
                std::cout << item1 + item2 << std::endl;

                return 0;
            }
        }
       
    1.23: Write a program that reads several transactions for the same ISBN. Write the sum of all the transactions that were read.
    Here is the code:
        #include <iostream>
        #include "Sales_item.h"

        int main(void)
        {
            Sales_item item;
            Sales_item sum;
            int count = 1;

            std::cout << "Please enter several record of sales as the following format:" << std::endl;
            std::cout << "[ISBN] [sales number] [per price]" << std::endl;
            std::cout << "After each record entered, you should enter a [ENTER]" << std::endl;

            while (std::cin >> item)
            {
                if (count == 1)
                {
                    sum = item;
                    ++count;
                }
                else if (sum.isbn != item.isbn)
                {
                    std::cout << "Wrong ISBN, please repeat your last input" << std::endl;
                    continue;
                }
                else if (count != 1)
                {
                    sum += item;
                    ++count;
                }
            }

            std::cout << "The summation of your input is:" << sum << std::endl;

            return 0;
        }
       
    When the suprised input happened or some error happened, the program should output some information or warning to point out what happened and how the stupid user make this, if this mistake will make the program shutdown, the  program should return a non0 value to indicates this unexpectional shutdown. in this situtation, the program should output to the stream named [std::cerr] or [std::clog] instead of [std::cout], which object should be used should be depend on what had happened. Although it's seems no difference on the screen by now. Actually, we have learned this in section 1.2.
   
    the Class Types has a special member differ in Struct Types, that is, [member functions], in C++, we prefer to named it [the methods of the class]. When we call a member function, we specify the object on which the function will operate. This syntax uses the [dot operator(.)]
   
Exercises Section 1.5.2
    1.24: Write a program that reads several transactions. For each new transaction that you read, determine if it is the same ISBN as the previous transaction, keeping a count of how many transactions there are for each ISBN. Test the program by giving multiple transactions. These transactions should represent multiple ISBNs but the records for each ISBN should be grouped together.
    Answer:
        We cannot ensure how many different ISBN the user will input, so the perfect version of this program should use the Array or something else in C++ that we haven't learned yet. so the following program code is an unperfect version, it can only statistics 3 or less different types of sales record.
    Here is the code:
        #include <iostream>
        #include "Sales_item.h"

        int main(void)
        {
            Sales_item record1, record2, record3;
            // the variable count1/2/3 is to notes how many records in record1/2/3
            int count1 = 0;
            int count2 = 0;
            int count3 = 0;
            Sales_item item;

            std::cout << "Please enter several record of sales as the following format:" << std::endl;
            std::cout << "[ISBN] [sales number] [per price]" << std::endl;
            std::cout << "After each record entered, you should enter a [ENTER]" << std::endl;
            std::cout << "If you want to terminate the input process, you should enter [CTRL + Z] and then [ENTER]" << std::endl;

            while (std::cin >> item)
            {
                if (count1 == 0)
                {
                    ++count1;
                    record1 = item;
                }
                else if (count1 != 0)
                {
                    if (record1.same_isbn(item))
                    {
                        ++count1;
                        record1 += item;
                    }
                    else if ( count2 == 0)
                    {
                        ++count2;
                        record2 = item;
                    }
                    else if (count2 != 0)
                    {
                        if (record2.same_isbn(item))
                        {
                            ++count2;
                            record2 += item;
                        }
                        else if (count3 == 0)
                        {
                            ++count3;
                            record3 = item;
                        }
                        else if (count3 != 0)
                        {
                            if (record3.same_isbn(item))
                            {
                                ++count3;
                                record3 += item;
                            }
                            else
                            {
                                std::cerr << "Input error, there are more than 3 types of book" << std::endl;
                                std::cerr << "Please check the lase input, fix the error, and enter again" << std::endl;
                                continue;
                            }
                        }
                    }
                }
            }

            std::cout << "The statistics result is:" << std::endl;
            std::cout << "[ISBN][Nums][Total $][Per $]" << std::endl;
            if (count1 != 0)
                std::cout << record1 << std::endl;
            if (count2 != 0)
                std::cout << record2 << std::endl;
            if (count3 != 0)
                std::cout << record3 << std::endl;

            return 0;
        }
       
Section 1.6. The C++ Program

    The program presented in this section taught me a skill, like this:
        if(std::cin >> trans)
        {
            while(std::cin >> trans)
            {
                ...;
                ...;
                ...;
            }
        }
        else
        {
            std::cerr << "ERROR, No data" << std::endl;
            return -1;
        }
       
Exercises Section 1.6:
    1.25: Using the Sales_item.h header from the Web site, compile and execute the bookstore program presented in this section.
    Answer:
        yeah, i do that, not a funny program.
       
    1.26: In the bookstore program we used the addition operator and not the compound assignment operator to add trans to total. Why didn't we use the compound assignment operator?
    Answer:
        Cause we just know that the header defines the [+] operator about the class type [Sales_item].
        we have no idea about whether the header defines the [+=] behaviour on the Sales_item class type. we'd better do not use [+=].
        but actually in the header [Sales_item.h], the [+=] operator has been defined correctly. Check the header, can found this:
            inline Sales_item & Sales_item::operator +=(const Sales_item &rhs)
            {
                units_sold += rhs.units_sold;
                revenue += rhs.revenue;
                return *this;
            }

           
Chapter 1 END.


0 0
原创粉丝点击