Google
 

Sunday, August 22, 2010

C++ Primer, Fourth Edition: Reading notes:Chapter 1. Getting Started

This chapter introduces most of the basic elements of C++: built-in, library, and class types; variables; expressions; statements; and functions. Along the way, we'll briefly explain how to compile and execute a program.

Having read this chapter and worked through the exercises, the reader should be able to write, compile, and execute simple programs.

Learning a new programming language requires writing programs.

1.1. Writing a Simple C++ Program

  1. The operating system uses the value returned by main to determine whether the program succeeded or failed. A return value of 0 indicates success.
  2. A function definition specifies four elements: the return type, the function name, a (possibly empty) parameter list enclosed in parentheses, and the function body. The main function may have only a restricted set of parameters.
  3. The main function is special in various ways, the most important of which are that the function must exist in every C++ program and it is the (only) function that the operating system explicitly calls.
    1. The main function is required to have a return type of int, which is the type that represents integers.
    2. The main function may have only a restricted set of parameters.
  4. On most systems, the return value from main is a status indicator.
    1. A return value of 0 indicates the successful completion of main.
    2. Any other return value has a meaning that is defined by the operating system.
    3. Usually a nonzero return indicates that an error occurred. Each operating system has its own way of telling the user what main returned
  5. How you compile a program depends on your operating system and compiler.
  6. The suffix for C++ program files depends on which compiler you're running. Other conventions include:prog1.cxx   prog1.cpp     prog1.cp     prog1.C
  7. Invoking the GNU or Microsoft Compilers
    1. By default the command to invoke the GNU compiler is g++: $ g++ prog1.cc -o prog1
    2. The Microsoft compilers are invoked using the command cl: C:\directory> cl -EHsc prog1.cpp
  8. Running the Compiler from the Command Line
    1. UNIX compilers tend to put their executables in a file named a.out. To run an executable we supply that name at the command-line prompt:   $ a.exe
    2. On UNIX systems you sometimes must also specify which directory the file is in, even if it is in the current directory. In such cases, we would write $ ./a.exe
    3. The value returned from main is accessed in a system-dependent manner. On both UNIX and Windows systems, after executing the program, you must issue an appropriate echo command.
      1. On UNIX systems, we obtain the status by writing     $ echo $? 
      2. To see the status on a Windows system, we write    C:\directory> echo %ERRORLEVEL%
  9. Exercises Section 1.1.1
  10. compile and run

Note:

  1. Semicolons mark the end of most statements in C++.

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 intended to be read from or written to an IO device of some kind. The term "stream" is intended to suggest that the characters are generated, or consumed, sequentially over time.

  1. Standard Input and Output Objects
    1. The library defines four IO objects.
    2. cin (pronounced "see-in"). This object is also referred to as the standard input.
    3. cout (pronounced "see-out"). It is often referred to as the standard output.
    4. The library also defines two other ostream objects, named cerr and clog (pronounced "see-err" and "see-log," respectively).The cerr object, referred to as the standard error, is typically used to generate warning and error messages to users of our programs.The clog object is used for general information about the execution of the program.
  2. A Program that Uses the IO Library
      #include <iostream>
      using namespace std;
      int main()
      {
      cout << "Please enter two numbers:" << endl;
      // the input should initialzie as 0, else
      // when the input the not integer, the sum will be redomly
      //int v1,v2;
      int v1(0),v2(0);
      cin >> v1 >> v2;
      // can be used like this style
      // The both style works same
      //cin >> v1 >> v2;
      //cin >> v1;
      //cin >> v2;

      cout << "The sum of "
      << v1
      << " and "
      << v2
      << " is "
      << v1 + v2
      << "."
      << endl;
      return 0;
      }

  3. The first line of our program is a preprocessor directive: #include <iostream>;which tells the compiler that we want to use the iostream library. The name inside angle brackets is a header. Every program that uses a library facility must include its associated header. The #include directive must be written on a single linethe name of the header and the #include must appear on the same line. In general, #include directives should appear outside any function. Typically, all the #include directives for a program appear at the beginning of the file.
  4. endl is a special value, called a manipulator, that when written to an output stream has the effect of writing a newline to the output and flushing the buffer associated with that device. By flushing the buffer, we ensure that the user will see the output written to the stream immediately.
  5. 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.
  6. Key Concept: Initialized and Uninitialized Variables

    1. Initialization is an important concept in C++ and one to which we will return throughout this book.
    2. Initialized variables are those that are given a value when they are defined.
    3. When we define a variable, we should give it an initial value unless we are certain that the initial value will be overwritten before the variable is used for any other purpose. If we cannot guarantee that the variable will be reset before being read, we should initialize it


Note



  1. When writing a C++ program, in most places that a space appears we could instead use a newline. One exception to this rule is that spaces inside a string literal cannot be replaced by a newline. Another exception is that spaces are not allowed inside preprocessor directives.

 


1.3. A Word About Comments




    1. Comments help the human readers of our programs. They are typically used to summarize an algorithm, identify the purpose of a variable, or clarify an otherwise obscure segment of code. Comments do not increase the size of the executable program. The compiler ignores all comments.
    2. Too many comments intermixed with the program code can obscure the code. It is usually best to place a comment block above the code it explains.
    3. Comments should be kept up to date as the code itself changes. Programmers expect comments to remain accurate and so believe them, even when other forms of system documentation are known to be out of date. An incorrect comment is worse than no comment at all because it may mislead a subsequent reader.

1.4. Control Structures



  1. 1.4.1. The while Statement

    1. while (condition) while_body_statement;
    2. A while executes by (repeatedly) testing the condition and executing the associated while_body_statement until the condition is false.
    3. the compound assignment operator, (the += operator). This operator adds its right-hand operand to its left-hand operand.
    4. the prefix increment operator (the ++ operator). The increment operator adds one to its operand.
    5. Key Concept: Indentation and Formatting of C++ Programs

      1. C++ programs are largely free-format, meaning that the positioning of curly braces, indentation, comments, and newlines usually has no effect on the meaning of our programs.
      2. Endless debates occur as to the right way to format C or C++ programs. Our belief is that there is no single correct style but that there is value in consistency. We tend to put the curly braces that delimit functions on their own lines. We tend to indent compound input or output expressions so that the operators line up,
      3. The important thing to keep in mind is that other ways to format programs are possible. When choosing a formatting style, think about how it affects readability and comprehension. Once you've chosen a style, use it consistently.


  2. 1.4.2. The for Statement

    1. In pre-Standard C++ names defined in a for header were accessible outside the for itself. This change in the language definition can surprise people accustomed to using an older compiler when they instead use a compiler that adheres to the standard.
    2. Compilation Revisited: The following are the most common kinds of errors a compiler will detect.

      1. Syntax errors.
      2. Type errors.
      3. Declaration errors. Every name used in a C++ program must be declared before it is used. Failure to declare a name usually results in an error message.
      4. An error message contains 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 fixor after making at most a small number of obvious fixes. This cycle is known as edit-compile-debug.


  3. 1.4.3. The if Statement
  4. 1.4.4. Reading an Unknown Number of Inputs
      #include <iostream>
      using namespace std;

      int main()
      {
      cout << "Please enter all numbers that you want to sum (just use ctrl+z to end your input sequence):" << endl;
      int val(0),sum(0);
      while( cin >> val)
      {
      sum += val;
      }
      cout << "The sum is " << sum << endl;
      // Issue :
      // when running how can I input end-of-file character on the screen to end the input?
      return 0;
      }


  5. When we use an istream as a condition, the effect is to test the state of the stream. If the stream is validthat is, if it is still possible to read another input then the test succeeds. An istream becomes invalid when we hit end-of-file 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 fail
  6. Entering an End-of-file from the Keyboard:Operating systems use different values for end-of-file. On Windows systems we enter an end-of-file by typing a control-z simultaneously type the "ctrl" key and a "z." On UNIX systems, including Mac OS-X machines, it is usually control-d.

1.5. Introducing Classes



  1. In C++ we define our own data structure by defining a class. The class mechanism is one of the most important features in C++. In fact, a primary focus of the design of C++ is to make it possible to define class types that behave as naturally as the built-in types themselves.
  2. 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?

  3. 1.5.1. The Sales_item Class

    1. Conventionally, class types are stored in a file with a name that, like the name of a program source file, has two parts: a file name and a file suffix. Usually the file name is the same as the class defined in the header. The suffix usually is .h, but some programmers use .H, .hpp, or .hxx.
    2. Key Concept: Classes Define Behavior

      1. As we go through these programs that use Sales_items, the important thing to keep in mind is that the author of the Sales_item class defined all the actions that can be performed by objects of this class. That is, the author of the Sales_item data structure defines what happens when a Sales_item object is created and what happens when the addition or the input and output operators are applied to Sales_item objects, and so on.
      2. In general, only the operations defined by a class can be used on objects of the class type. For now, the only operations we know we can peeform on Sales_item objects are the ones listed on page 21.

    3. A member function is a function that is defined by a class. Member functions are sometimes referred to as the methods of the class.
    4. Member functions are defined once for the class but are treated as members of each object. We refer to these operations as member functions because they (usually) operate on a specific object. In this sense, they are members of the object, even though a single definition is shared by all objects of the same type.
    5. When we call a member function, we (usually) specify the object on which the function will operate. This syntax uses the dot operator (the "." operator)
    6. The dot operator applies only to objects of class type: The left-hand operand must be an object of class type; the right-hand operand must name a member of that type.
    7. Unlike most other operators, the right operand of the dot (".") operator is not an object or value; it is the name of a member.


1.6. The C++ Program


Exercises Section:


Exercise 1.3:

#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
return 0;
}
Exercise 1.4:
#include <iostream>
using namespace std;

int main()
{
cout << "Please enter two numbers:" << endl;
int a(0),b(0);

cin >> a >> b;

cout << "The product of " << a << " and " << b << " is " << a * b << endl;
return 0;
}

Exercise 1.5:


Exercise 1.6:

	// should be the following
std::cout << "The sum of " << v1
<< " and " << v2
<< " is " << v1 + v2
<< std::endl;
Exercise 1.8:
#include <iostream>

int main()
{
std::cout << "/*";
std::cout << "*/";
// the third is incorrect!
//std::cout << /* "*/" */;

return 0;
}
Exercise 1.9:
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
for (int i = -100; i <= 100; ++i)
{
sum += i;
}
cout << "The sum is " << sum << endl;
return 0;
}

Exercise 1.10:

#include<iostream>
using namespace std;

int main()
{
int sum(0),i(50);
while(i<=100)
{
sum+=i;
i++;
}
cout<<"The sum from 50 to 100 is "<< sum <<endl;
return 0;
}

//#include <iostream>
//using namespace std;
//
//int main()
//{
// int sum(0);
// for (int i = 50 ;i <= 100; ++i )
// {
// sum +=i;
// }
// cout << "The sum from 50 to 100 is " << sum << endl;
// return 0;
//}


Exercise 1.11:

#include <iostream>
using namespace std;

int main()
{
for (int i = 10 ; i >= 0 ; --i)
{
cout << i << endl;
}
//int i(10);
//while(i >=0)
//{
// cout << i-- << endl;
//}
return 0;
}
Exercise 1.12:

Exercise 1.16:

#include<iostream>
using namespace std;

int main()
{
cout << "Please enter two numbers:" << endl;
int v1(0),v2(0);
cin >> v1 >> v2;

int larger(0);
if(v1 > v2)
{
larger = v1;
}
else if ( v1 == v2)
{
cout << "The two numbers " << v1 << " and " << v2 << " are equal!";
return 0;
}
else
{
larger = v2;
}
cout << "The bigger is " << larger << " of the two numbers " << v1 << " and " << v2 << endl;
return 0;
}

Exercise 1.17:

#include <iostream>
using namespace std;

//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.

int main()
{
cout << "Please enter a series of numbers:" << endl;
int val(0);
int times(0);
while(cin >> val)
{
if(val < 0)
{
times++;
}
}
cout << "There are totally " << times << " negative numbers!" << endl;
return 0;
}
Exercise 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.

#include <iostream>
using namespace std;

int main()
{
cout << "Please input the range:" << endl;
int lower(0),larger(0);
cin >> lower >> larger;
if(lower > larger)
{
int tmp = lower;
lower = larger;
larger = tmp;
}
cout << "The numbers in the range of the two numbers " << lower << " and " << larger << " are:" << endl;
for ( int val = lower; val <= larger;++val)
{
cout << val << endl;
}
return 0;
}
Exercise 1.19:
Exercise 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 numbers 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.
#include <iostream>
int main()
{
std::cout << "Enter two numbers:" << std::endl;
int v1, v2;
std::cin >> v1 >> v2; // read input
// use smaller number as lower bound for summation
// and larger number as upper bound
int lower(v1), upper(v2);
//if (v1 <= v2) {
// lower = v1;
// upper = v2;
//} else {
// lower = v2;
// upper = v1;
//}
int sum = 0;
// sum values from lower up to and including upper
for (int val = lower; val <= upper; ++val)
sum += val; // sum = sum + val

std::cout << "Sum of " << lower
<< " to " << upper
<< " inclusive is "
<< sum << std::endl;
return 0;
}
Exercise 1.21:
#include <iostream>
#include "Sales_item.h"
using namespace std;

/*
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.
*/

int main()
{
Sales_item item;
int max(100);
Sales_item itemArray[100];
int times(0);
while(cin >> item && times < max)
{
//cout<< item1 << endl;
itemArray[times++] = item;
}
cout << "All your input are:" << endl;
cout << "Totally " << times << " Sales items" <<endl;
while(times >= 0)
{
cout << itemArray[times--] << endl;
}
return 0;
}
Exercise 1.22:
//Write a program that reads two Sales_item objects that have the same ISBN and produces their sum.
#include <iostream>
#include "Sales_item.h"
using namespace std;

int main()
{
cout << "Please enter two same sales item:" << endl;
Sales_item item1 , item2;
cin >> item1 >> item2;

if( item1.same_isbn(item2))
{
cout << "The sum of " << item1 << " and " << item2 << " is " << item1 + item2 << endl;
}
else
{
cout << "Your input are not the same ISBN!" << endl;
}
return 0;
}
Exercise 1.23:
//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"
#include <iostream>
using namespace std;

int main()
{
cout << "Please input your sales item to sum:" << endl;
Sales_item trans, sum;
int times(1);
if(cin >> sum)
{
while(cin >> trans)
{
if(sum.same_isbn(trans))
{
sum += trans;
times++;
}
else
{
cout << "Your input must the same as your first input ISBN!" << endl;
sum = trans;
}
}
cout << "Totally " << times << " items you have entered!" << endl;
cout << "The sum is " << sum << endl;
}
else
{
cout << "No data!" << endl;
return -1;
}
return 0;
}
Exercise 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.

*/

#include "Sales_item.h"
#include <iostream>
using namespace std;

int main()
{
cout << "Please input your sales item to sum:" << endl;
Sales_item trans, sum;
int times(1);
if(cin >> sum)
{
while(cin >> trans)
{
if(sum.same_isbn(trans))
{
sum += trans;
}
else
{
cout << "Your input must the same as your first input ISBN!" << endl;
// I don't think here the sum should be updated!
//sum = trans;
}
times++;
}
cout << "Totally " << times << " items you have entered!" << endl;
cout << "The sum is " << sum << endl;
}
else
{
cout << "No data!" << endl;
return -1;
}
return 0;
}
Exercise 1.25:?
Exercise 1.26:?

No comments: