2011年12月21日 星期三

Getting Started (I)


To get started with C++, we should dive right in, start writing code and see what's new. This section will address four differences between C and C++.
  • Writing comments in a C++ program
  • Using cin and cout for input and output to a C++ program (and #include <iostream>)
  • Declaring variables almost anywhere
  • Using type bool for true or false

Comments in a C++ program

In C, you learned to use the /* … */ style comment. Since C++ includes the C language syntax, you can, of course, use the same style comments, but C++ also includes its own style of writing a program comment. This is accomplished using //. The // can be used any place on a program line to mean that anything to the right of the // is intended to be a comment and not part of the program – not compiled. An entire line may be commented, like this:

// see, this is a comment consisting of an entire line
or part of a line like this:

if (b * b – 4 * a * c < 0) {        // make sure the determinant is not negative
You can use either C-style comments, /* … */, or C++ style comments or both in your program. The advantage of the C-style comment is that the comment can be long and span many lines, and the advantage of the C++ comment is that it's easier, two keystrokes instead of four. Besides, this is all about C++ anyway. There is one word of caution. Be careful of nesting the two styles. For example, this is OK.

/* this is a one-line comment */

/* this is
    a comment that
    goes on and on,
    and ends on this line */

/* Here's another comment // and what's this?
    Oh, who cares?
    That's all folks */

Now, here's the rub:

// this is OK

/* nothing wrong with
    this comment
*/

// This is a C++ style comment /* and now let's do a
    C-style comment */

/* Here's another
// screw up */

Do you see the problem? Just be careful.

cin and cout

In learning C, you probably started with scanf() and printf() for input and output. In C++, we will do the same thing with cin and cout. cin will be used for input from the keyboard and cout for output to the screen.

In C, it looks like this:

printf("Enter some number\n");
scanf("%d",&i);

In C++, like this:

cout << "Enter some number\n";
cin >> i;

scanf() and printf() are functions. cin and cout are not function they are things, or more precisely, objects. You can think of them as the keyboard and monitor (or screen). To be more precise, cin is an object of type istream and cout is an object of type ostream. And what about << and >>? These guys (guys is a technical term, more precisely, a male technical term) are operators, just like the + in x + y. And in case you wanted to know, operators, in C++ can be the same thing as functions.

So, of course, our two lines of code, displays Enter some number on the screen and the program stops, waiting for the user to enter a number. It acts just like the C code.

One more point, cin and cout are not free, just like printf() and scanf() are not free. To use printf() and scanf() you must include the header file, <stdio.h>. Similarly, in C++, for cin and cout, you will need to include the header file, <iostream>. Note that it is <iostream>, not <iostream.h>. We'll get to that later.

What exactly is cin and cout?

Consider the statements,

int age;
cin >> age;
cout << "I am " << age << " years old." << endl;

In C we would write,

int age;
scanf("%d",&age);
printf("I am %d years old.\n",39);

These two statements do the same thing. cin and cout are objects. This means that they are variables of a certain type (specially they are variables of type istream and ostream). They are not functions, like printf() and scanf(). The function part of the statements is the >> and << operators. And, while we're at it, endl is almost the same as \n.

Declaring variables where you want

In C you learned to declare variables at the beginning of a function and in C++ you can do the same thing. That, of course, would be too boring. So, there's another way. You can declare variables where you need them. Variables do not have to be declared at the beginning of your program, or the beginning of a function, or at the top of a block. They can be declared just before you use them. Of course, you can't declare them after you use them. For example, in C you would:

int x;
printf("Enter some number\n");
scanf("%d",&x);

And is C++, you can do this:

printf("Enter some number\n");
int x;
scanf("%d",&x);

There is the advantage or declaring variables at the top of a function. The reader of the code (that might be you in six months), knows where to look for variable declarations. On the other hand, being able to declare variable any old time allows you to write code without a lot of up front planning. That's a good thing, right?

Type bool

ANSI/ISO C++ includes a type called bool to store true-false values. This concept has been around forever in programming and in C and even C++.  I guess the only issue was settling on the name of the type. An obvious application might look like this:


bool rich;
rich = money > 1000000;
if (rich) {
  cout << "Whoopee!";
}

Here is the first example that demonstrates the some initial C++ concepts and some differences between C and C++.

Example 1-1

1      // File:  Ex1-1.cpp
2     
3      // Illustrates some of the basic differences between C and C++:
4      // Comments
5      // cin and cout for input and output
6      // declarations of variables almost anywhere
7      // use of type bool
8     
9      #include <iostream>        // instead of <stdio.h> or <iostream.h>
10      using namespace std;
11     
12      /* You can still use the old comment, */
13     
14      /* but you must be // very careful
15      about mixing them */
16     
17      // Your best bet is to use this style for 1 line or a partial line
18      /* And use this style when your comment
19      consists of multiple lines */
20     
21      int main (void)
22      {
23          cout << "hey";            // Why won't printf or puts work here?
24          //printf("hey");
25          //puts("hey");      // Can you use printf or puts in a C++ program?
26         
27          for (int k = 1; k < 5; k++)    // declare a variable when you need it
28          {
29              cout << k;
30          }
31          //cout << k;
32          cout << endl;            // print a carriage return (newline)
33         
34          cout << "Please enter your name => ";
35         
36          char name[10];            // I feel like declaring a variable
37         
38          cin >> name;
39         
40          cout << "Hey " << name << ", nice name." << endl;
41         
42          cout << endl;            // blank line
43         
44          cout << "Hey " << name << ", how old are you? ";
45         
46          int age;            // Declare another variable
47          cin >> age;
48         
49          bool IsOld = age > 35;
50          bool IsYoung = !IsOld;
51          cout << IsOld << ' ' << IsYoung << endl;
52         
53          if (IsOld) cout << name << ", you don't really look that old!\n;
54         
55          char dogs_name[10];
56          int cats;
57         
58          cout << "What's your dog's name and how many cats do you have? "
59              << endl;
60         
61          cin >> dogs_name >> cats;
62         
63          cout << "I'll bet " << dogs_name << " is a good dog and your "
64               << cats << " cat" << (cats>1?"s are":" is") << " nice too\n";
65         
66          {
67              // This is a block
68              int x = 5;    // x is local to this block
69              cout << x;
70          }
71         
72          // cout << x;     What would happen if you tried to print x now?
73         
74          return 0;
75      } 

*****  Sample Run  *****

hey1234
Please enter your name => Joe
Hey Joe, nice name.

Hey Joe, how old are you? 34
0 1
What's your dog's name and how many cats do you have?
Bart 2
I'll bet Bart is a good dog and your 2 cats are nice too
5

Note: cin is similar to scanf(), but does not require conversion specifiers and whitespace is a separator for multiple variables. cin does not require the address operator (&), like scanf().

<< ("left-shift" in C) is called the insertion operator. >> ("right shift") is called the extraction operator.

Note on for loops with MS Visual C++ 6.0: First of all, you should not be using MS Visual C++, it's too old. But, if you insist, the following code does not work according to the C++ "standard". The "standard" specifies that k will only "have scope" for the for loop, and after completion of the for loop, k will be undefined. MS Visual C++ 6.0 doesn't see it that way. You've been warned!

for (int k = 1; k < 5; k++)
{
   cout << k;
}

C++ 與 C 不同處:
  • comments 的寫法
  • 使用 cin and cout 來輸入和輸出 (#include <iostream>)
  • 隨時可以定義變數
  • 資料形態 bool 值為 true 或 false

沒有留言:

張貼留言