Beginning C++ Through Came Programminghtml
2017.03.14 - 2017.03.17node
簡單編程熟悉概念,四天所有看完。ios
(001) 致謝c++
贈人玫瑰,手有餘香
算法
Finally, I want to thank all of the game programmers who created the games I played while growing up. They inspired me to work in the industry and create games of my own. I hope I can inspire a few readers to do the same.express
(002) 目錄編程
Chapter 01: Types, Variables, and Standard I/O: Lost Fortune數組
Chapter 02: Truth, Branching, and the Game Loop: Guess My Numbersession
Chapter 03: for Loops, Strings, and Arrays: Word Jumbleapp
Chapter 04: The Standard Template Library: Hangman
Chapter 05: Functions: Mad Lib
Chapter 06: References: Tic-Tac-Toe
Chapter 07: Pointers: Tic-Tac-Toe 2.0
Chapter 08: Classes: Critter Caretaker
Chapter 09: Advanced Classes and Dynamic Memory: Game Lobby
Chapter 10: Inheritance and Polymorphism: Blackjack
Appendix
(003) C++語言對於遊戲的重要性
If you were to wander the PC game section of your favorite store and grab a title at random, the odds are overwhelming that the game in your hand would be written largely or exclusively in C++.
(004) 本書目標
The goal of this book is to introduce you to the C++ language from a game programming perspective.
By the end of this book, you'll have a solid foundation in the game programming language of the professionals.
Chapter 1: Types, Variables, And Standard I/O: Lost Fortune
(005) 第一個遊戲
The Game Over program puts a gaming twist on the classic and displays Game Over! instead.
- 1 // Game Over
- 2 // A first C++ program
- 3 #include <iostream>
- 4
- 5 int main()
- 6 {
- 7 std::cout << "Game Over!" << std::endl;
- 8 return 0;
- 9 }
wang@wang:~/workspace/beginc++game$ ./game_over
Game Over!
(006) ostream
cout is an object, defined in the file iostream, that's used to send data to the standard output stream.
(007) 使用std directive
- 1 // Game Over 2.0
- 2 // Demonstrates a using directive
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 cout << "Game Over!" << endl;
- 10 return 0;
- 11 }
wang@wang:~/workspace/beginc++game$ ./game_over2
Game Over!
(008) 使用using declaration
- 1 // Game Over 3.0
- 2 // Demonstrates using declarations
- 3
- 4 #include <iostream>
- 5 using std::cout;
- 6 using std::endl;
- 7
- 8 int main()
- 9 {
- 10 cout << "Game Over!" << endl;
- 11 return 0;
- 12 }
wang@wang:~/workspace/beginc++game$ ./game_over3
Game Over!
(009) 加減乘除
- 1 // Expensive Calculator
- 2 // Demonstrates built-in arithmetic operators
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 cout << "7 + 3 = " << 7 + 3 << endl;
- 10 cout << "7 - 3 = " << 7 - 3 << endl;
- 11 cout << "7 * 3 = " << 7 * 3 << endl;
- 12
- 13 cout << "7 / 3 = " << 7 / 3 << endl;
- 14 cout << "7.0 / 3.0 = " << 7.0 / 3.0 << endl;
- 15
- 16 cout << "7 % 3 = " << 7 % 3 << endl;
- 17
- 18 cout << "7 + 3 * 5 = " << 7 + 3 * 5 << endl;
- 19 cout << "(7 + 3) * 5 = " << (7 + 3) * 5 << endl;
- 20
- 21 return 0;
- 22 }
wang@wang:~/workspace/beginc++game$ ./expensive_calculator
7 + 3 = 10
7 - 3 = 4
7 * 3 = 21
7 / 3 = 2
7.0 / 3.0 = 2.33333
7 % 3 = 1
7 + 3 * 5 = 22
(7 + 3) * 5 = 50
(010) 變量
A variable represents a particular piece of your computer's memory that has been set aside for you to use to store, retrieve, and manipulate data.
(011) 狀態值舉例
- 1 // Game Stats
- 2 // Demonstrates declaring and initializing variables
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int score;
- 10 double distance;
- 11 char playAgain;
- 12 bool shieldsUp;
- 13
- 14 short lives, aliensKilled;
- 15
- 16 score = 0;
- 17 distance = 1200.76;
- 18 playAgain = 'y';
- 19 shieldsUp = true;
- 20 lives = 3;
- 21 aliensKilled = 10;
- 22 double engineTemp = 6572.89;
- 23
- 24 cout << "score: " << score << endl;
- 25 cout << "distance: " << distance << endl;
- 26 cout << "playAgain: " << playAgain << endl;
- 27 // skipping shieldsUp since you don't generally print Boolean values
- 28 cout << "lives: " << lives << endl;
- 29 cout << "aliensKilled: " << aliensKilled << endl;
- 30 cout << "engineTemp: " << engineTemp << endl;
- 31
- 32 int fuel;
- 33 cout << "How much fuel? ";
- 34 cin >> fuel;
- 35 cout << "fuel: " << fuel << endl;
- 36
- 37 typedef unsigned short int ushort;
- 38 ushort bonus = 10;
- 39 cout << "bonus: " << bonus << endl;
- 40
- 41 return 0;
- 42 }
wang@wang:~/workspace/beginc++game$ ./game_stats
score: 0
distance: 1200.76
playAgain: y
lives: 3
aliensKilled: 10
engineTemp: 6572.89
How much fuel? 12
fuel: 12
bonus: 10
(012) modifier
signed and unsigned are modifiers that work only with integer types.
(013) identifier命名規則
1. Choose descriptive names
2. Be consistent
3. Follow the traditions of the language
4. Keep the length in check
(014) typedef定義
To define new names for existing types, use typedef followed by the current type, followed by the new name.
(015) 變量運算舉例
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 unsigned int score = 5000;
- 10 cout << "score: " << score << endl;
- 11
- 12
- 13 score = score + 100;
- 14 cout << "score: " << score << endl;
- 15
- 16
- 17 score += 100;
- 18 cout << "score: " << score << endl;
- 19
- 20
- 21 int lives = 3;
- 22 ++lives;
- 23 cout << "lives: " << lives << endl;
- 24
- 25 lives = 3;
- 26 lives++;
- 27 cout << "lives: " << lives << endl;
- 28
- 29 lives = 3;
- 30 int bonus = ++lives * 10;
- 31 cout << "lives, bonus = " << lives << ", " << bonus << endl;
- 32
- 33 lives = 3;
- 34 bonus = lives++ * 10;
- 35 cout << "lives, bonus = " << lives << ", " << bonus << endl;
- 36
- 37
- 38 score = 4294967295;
- 39 cout << "socre: " << score << endl;
- 40 ++score;
- 41 cout << "score: " << score << endl;
- 42
- 43 return 0;
- 44 }
wang@wang:~/test$ ./game_stat2
score: 5000
score: 5100
score: 5200
lives: 4
lives: 4
lives, bonus = 4, 40
lives, bonus = 4, 30
socre: 4294967295
score: 0
(016) wrap around溢出
Make sure to pick an integer type that has a large enough range for its intended use.
(017) 常量
First, they make programs clearer.
Second, constants make changes easy.
(018) 枚舉類型舉例
An enumeration is a set of unsigned int constants, called enumerators.
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 const int ALIEN_POINTS = 150;
- 10 int aliensKilled = 10;
- 11 int score = aliensKilled * ALIEN_POINTS;
- 12 cout << "score: " << score << endl;
- 13 enum difficulty {NOVICE, EASY, NORMAL, HARD, UNBEATABLE};
- 14 difficulty myDifficulty = EASY;
- 15 enum shipCost {FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50};
- 16 shipCost myShipCost = BOMBER_COST;
- 17 cout << "To upgrade my ship to a Cruiser will cost "
- 18 << (CRUISER_COST - myShipCost) << " Resource Points.\n";
- 19 return 0;
- 20 }
wang@wang:~/test$ ./game_stats3
score: 1500
To upgrade my ship to a Cruiser will cost 24 Resource Points.
(019) 綜合舉例
有趣的文字遊戲
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6
- 7 using namespace std;
- 8 int main()
- 9 {
- 10 const int GOLD_PIECES = 900;
- 11 int adventurers, killed, survivors;
- 12 string leader;
- 13
- 14
- 15 cout << "Welcome to Lost Fortune\n";
- 16 cout << "Please enter the following for your personalized adventure\n";
- 17 cout << "Enter a number: ";
- 18 cin >> adventurers;
- 19 cout << "Enter a number, smaller than the first: ";
- 20 cin >> killed;
- 21 survivors = adventurers - killed;
- 22 cout << "Enter your last name: ";
- 23 cin >> leader;
- 24
- 25 cout << "A brave group of " << adventurers << " set out on a quest ";
- 26 cout << "-- in search of the lost treasure of the Ancient Dwarves. ";
- 27 cout << "The group was led by that legendary rogue, " << leader << ".\n";
- 28 cout << "Along the way, a band of marauding ogres ambushed the party. ";
- 29 cout << "All fought bravely under the command of " << leader;
- 30 cout << ", and the ogres were defeated, but at a cost. ";
- 31 cout << "Of the adventurers, " << killed << " were vanquished, ";
- 32 cout << "leaving just " << survivors << " in the group.\n";
- 33 cout << "The party was about to give up all hope. ";
- 34 cout << "But while laying the deceased to rest, ";
- 35 cout << "they stumbled upon the buried fortune. ";
- 36 cout << "So the adventurers split " << GOLD_PIECES << " gold pieces. ";
- 37 cout << leader << " held on to the extra " << (GOLD_PIECES % survivors);
- 38 cout << " pieces to keep things fair of cource.\n";
- 39 return 0;
- 40 }
wang@wang:~/test$ g++ lost_fortune.cpp -o lost_fortune
wang@wang:~/test$ ./lost_fortune
Welcome to Lost Fortune
Please enter the following for your personalized adventure
Enter a number: 19
Enter a number, smaller than the first: 13
Enter your last name: wang
A brave group of 19 set out on a quest -- in search of the lost treasure of the Ancient Dwarves. The group was led by that legendary rogue, wang.
Along the way, a band of marauding ogres ambushed the party. All fought bravely under the command of wang, and the ogres were defeated, but at a cost. Of the adventurers, 13 were vanquished, leaving just 6 in the group.
The party was about to give up all hope. But while laying the deceased to rest, they stumbled upon the buried fortune. So the adventurers split 900 gold pieces. wang held on to the extra 0 pieces to keep things fair of cource.
(020) 習題
1. enum names {WORST, WORSR, BAD, GOOD, BETTER, BEST};
2. 2, 2.333333, 2.333333
3. 輸入三個整數,輸出它們的平均值
- 1 #include <iostream>
- 2 using namespace std;
- 3
- 4 int main()
- 5 {
- 6 int firstScore, secondScore, thirdScore;
- 7 cout << "Enter three integers: ";
- 8 cin >> firstScore >> secondScore >> thirdScore;
- 9 int average = (firstScore + secondScore + thirdScore) / 3;
- 10 cout << average << endl;
- 11 return 0;
- 12 }
wang@wang:~/test$ ./three_score
Enter three integers: 1 2 3
2
Chapter 2: Truth, Branching, And The Game Loop: Guess My Number
(021) if (expression) statement;
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 if (true) {
- 10 cout << "This is always displayd.\n";
- 11 }
- 12 if (false) {
- 13 cout << "This is never displayed.\n";
- 14 }
- 15
- 16 int score = 1000;
- 17 if (score) {
- 18 cout << "At least you didn't score zero.\n";
- 19 }
- 20 if (score > 250) {
- 21 cout << "You scored 250 more. Decent.\n";
- 22 }
- 23 if (score >= 500) {
- 24 cout << "You scored 500 or more. Nice.\n";
- 25 if (score >= 1000) {
- 26 cout << "You scored 1000 or more. Impressive!\n";
- 27 }
- 28 }
- 29 return 0;
- 30 }
wang@wang:~/test$ g++ score_rater.cpp -o score_rater
wang@wang:~/test$ ./score_rater
This is always displayd.
At least you didn't score zero.
You scored 250 more. Decent.
You scored 500 or more. Nice.
You scored 1000 or more. Impressive!
(022) else 語句
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int score;
- 10 cout << "Enter your score: ";
- 11 cin >> score;
- 12
- 13 if (score >= 1000) {
- 14 cout << "You scored 1000 or more. Impressive!\n";
- 15 } else {
- 16 cout << "You score less than 1000.\n";
- 17 }
- 18 return 0;
- 19 }
wang@wang:~/test$ ./score_rater2
Enter your score: 456
You score less than 1000.
(023) 多個if語句
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int score;
- 10 cout << "Enter your score: ";
- 11 cin >> score;
- 12
- 13 if (score >= 1000) {
- 14 cout << "You scored 1000 or more. Impressive!\n";
- 15 } else if (score >= 500) {
- 16 cout << "You score 500 or more. Nice.\n";
- 17 } else if (score >= 250) {
- 18 cout << "You score 250 or more. Decent.\n";
- 19 } else
- 20 cout << "You scored less than 250. Nothing to brag about.\n";
- 21 return 0;
- 22 }
wang@wang:~/test$ ./score_rater3
Enter your score: 100
You scored less than 250. Nothing to brag about.
(024) switch語句舉例
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 cout << "Difficulty Levels\n";
- 10 cout << "1 - Easy\n";
- 11 cout << "2 - Normal\n";
- 12 cout << "3 - Hard\n";
- 13
- 14 int choice;
- 15 cout << "Choice: ";
- 16 cin >> choice;
- 17
- 18 switch (choice) {
- 19 case 1:
- 20 cout << "You picked Easy.\n";
- 21 break;
- 22 case 2:
- 23 cout << "You picked Normal.\n";
- 24 break;
- 25 case 3:
- 26 cout << "You picked Hard.\n";
- 27 default:
- 28 cout << "You made an illegal choice.\n";
- 29 }
- 30 return 0;
- 31 }
wang@wang:~/test$ ./menu_chooser
Difficulty Levels
1 - Easy
2 - Normal
3 - Hard
Choice: 2
You picked Normal.
(025) while 循環舉例
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 char again = 'y';
- 10 while (again == 'y') {
- 11 cout << "**Played an exciting game**\n";
- 12 cout << "Do you want to play again? (y/n): ";
- 13 cin >> again;
- 14 }
- 15 cout << "Okay, bye.\n";
- 16 return 0;
- 17 }
wang@wang:~/test$ ./play_again
**Played an exciting game**
Do you want to play again? (y/n): y
**Played an exciting game**
Do you want to play again? (y/n): b
Okay, bye.
(026) do while循環
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 char again;
- 10 do {
- 11 cout << "**Played an exciting game**";
- 12 cout << "\nDo you want to play again? (y/n): ";
- 13 cin >> again;
- 14 } while (again == 'y');
- 15
- 16 cout << "Okay, bye.\n";
- 17 return 0;
- 18 }
wang@wang:~/test$ ./play_again2
**Played an exciting game**
Do you want to play again? (y/n): y
**Played an exciting game**
Do you want to play again? (y/n): n
Okay, bye.
(027) break & continue
You can immediately exit a loop with the break statement, and you can jump directly to the top of a loop with a continue statement.
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int count = 0;
- 10 while (true) {
- 11 count += 1;
- 12
- 13 if (count > 10)
- 14 break;
- 15
- 16 if (count == 5)
- 17 continue;
- 18 cout << count << endl;
- 19 }
- 20 return 0;
- 21 }
wang@wang:~/test$ ./finicky_counter
1
2
3
4
6
7
8
9
10
(028) 邏輯運算符&& || !
Logical NOT, ! has a higher level of precedence that logical AND, &&, which has a higher precedence than logical OR, ||.
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6
- 7 using namespace std;
- 8
- 9 int main()
- 10 {
- 11 string username;
- 12 string password;
- 13 bool success;
- 14 cout << "\tGame Designer's Network\n";
- 15 do {
- 16 cout << "Username: ";
- 17 cin >> username;
- 18 cout << "Password: ";
- 19 cin >> password;
- 20
- 21 if (username == "S.Meier" && password == "civilization") {
- 22 cout << "Hey, Sid.\n";
- 23 success = true;
- 24 } else if (username == "S.Miyamoto" && password == "mariobros") {
- 25 cout << "What's up, Shigegu?\n";
- 26 success = true;
- 27 } else if (username == "guest" || password == "guest") {
- 28 cout << "Welcome, guest.\n";
- 29 success = true;
- 30 } else {
- 31 cout << "Your login failed.\n";
- 32 success = false;
- 33 }
- 34 } while (!success);
- 35 return 0;
- 36 }
wang@wang:~/test$ ./designers_network
Game Designer's Network
Username: wang
Password: wang
Your login failed.
Username: wang
Password: guest
Welcome, guest.
(029) 產生隨機數
The file sctdlib contains (among other things) functions that deal with generating random numbers.
The upper limit is stored in the constant RAND_MAX.
In terms of the actual code, the srand() function seeds the random number generator.
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <cstdlib>
- 6 #include <ctime>
- 7 using namespace std;
- 8
- 9 int main()
- 10 {
- 11
- 12 srand(static_cast<unsigned int> (time(0)));
- 13 int randomNumber = rand();
- 14
- 15 int die = (randomNumber % 6) + 1;
- 16 cout << "You rolled a " << die << endl;
- 17 return 0;
- 18 }
wang@wang:~/test$ ./die_roller
You rolled a 3
wang@wang:~/test$ ./die_roller
You rolled a 3
wang@wang:~/test$ ./die_roller
You rolled a 6
(030) 猜數字遊戲,適合三歲小孩子玩。
- 1
- 2
- 3 #include <iostream>
- 4 #include <cstdlib>
- 5 #include <ctime>
- 6 using namespace std;
- 7
- 8 int main()
- 9 {
- 10
- 11 srand(static_cast<unsigned int>(time(0)));
- 12
- 13 int secretNumber = rand() % 100 + 1;
- 14 int tries = 0;
- 15 int guess;
- 16 cout << "\tWelcome to Guess My Number\n";
- 17 do {
- 18 cout << "Enter a guess: ";
- 19 cin >> guess;
- 20 ++tries;
- 21 if (guess > secretNumber)
- 22 cout << "Too high!\n";
- 23 else if (guess < secretNumber)
- 24 cout << "Too low!\n";
- 25 else
- 26 cout << "That's it! you got it in " << tries << " guesses!\n";
- 27 } while (guess != secretNumber);
- 28 return 0;
- 29 }
wang@wang:~/test$ ./guess_my_number
Welcome to Guess My Number
Enter a guess: 56
Too high!
Enter a guess: 28
Too high!
Enter a guess: 14
Too high!
Enter a guess: 8
Too high!
Enter a guess: 4
Too high!
Enter a guess: 2
Too low!
Enter a guess: 3
That's it! you got it in 7 guesses!
(031) 習題
1. 使用enum表示。
- 1 #include <iostream>
- 2 using namespace std;
- 3
- 4 int main()
- 5 {
- 6 cout << "Difficult Levels\n";
- 7 cout << "1 - Easy\n";
- 8 cout << "2 - Normal\n";
- 9 cout << "3 - Hard\n";
- 10 enum level {EASY = 1, NORMAL, HARD};
- 11 int choice;
- 12 cout << "Choice: ";
- 13 cin >> choice;
- 14 switch (choice) {
- 15 case EASY:
- 16 cout << "You picked Easy.\n";
- 17 break;
- 18 case NORMAL:
- 19 cout << "You picked Normal.\n";
- 20 break;
- 21 case HARD:
- 22 cout << "You picked Hard.\n";
- 23 default:
- 24 cout << "You made an illegal choice.\n";
- 25 }
- 26 return 0;
- 27 }
wang@wang:~/test$ ./menulevel
Difficult Levels
1 - Easy
2 - Normal
3 - Hard
Choice: 2
You picked Normal.
2. 沒有進入while循環中。
3. 用戶提供數據,電腦猜
- 1
- 2
- 3 #include <iostream>
- 4 #include <cstdlib>
- 5 #include <ctime>
- 6 using namespace std;
- 7
- 8 int main()
- 9 {
- 10 int number;
- 11 cout << "Enter a number (1 - 10): ";
- 12 cin >> number;
- 13 int tries = 0;
- 14 int guess;
- 15 cout << "\tWelcome to Guess My Number\n";
- 16 do {
- 17
- 18 srand(static_cast<unsigned int>(time(0)));
- 19
- 20 guess = rand() % 10 + 1;
- 21 ++tries;
- 22 if (guess > number)
- 23 cout << "Too high!\n";
- 24 else if (guess < number)
- 25 cout << "Too low!\n";
- 26 else
- 27 cout << "That's it! you got it in " << tries << " guesses!\n";
- 28 } while (guess != number);
- 29 return 0;
- 30 }
隨機猜猜的次數太多。
That's it! you got it in 300166 guesses!
Chapter 3: For Loops, Strings, And Arrays: Word Jumble
(032) for循環
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 cout << "Count forward: ";
- 10 for (int i = 0; i < 10; ++i)
- 11 cout << i << " ";
- 12 cout << "\nCounting backward: ";
- 13 for (int i = 9; i >= 0; --i)
- 14 cout << i << " ";
- 15 cout << "\nCounting by fives: ";
- 16 for (int i = 0; i <= 50; i += 5)
- 17 cout << i << " ";
- 18 cout << "\nCounting with null statements: ";
- 19 int count = 0;
- 20 for (; count < 10;) {
- 21 cout << count << " ";
- 22 ++count;
- 23 }
- 24 cout << "\nCounting with nested for loops:\n";
- 25 const int ROWS = 5;
- 26 const int COLUMNS = 3;
- 27 for (int i = 0; i < ROWS; ++i) {
- 28 for (int j = 0; j < COLUMNS; ++j) {
- 29 cout << i << "," << j << " ";
- 30 }
- 31 cout << endl;
- 32 }
- 33 return 0;
- 34 }
wang@wang:~/test$ ./counter
Count forward: 0 1 2 3 4 5 6 7 8 9
Counting backward: 9 8 7 6 5 4 3 2 1 0
Counting by fives: 0 5 10 15 20 25 30 35 40 45 50
Counting with null statements: 0 1 2 3 4 5 6 7 8 9
Counting with nested for loops:
0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
3,0 3,1 3,2
4,0 4,1 4,2
(033) string 對象的用法
string 幾種不一樣的初始化方式。
earse第一個參數是位置,第二個參數是個數。
When using find(), you can supply an optional argument that specifies a character number for the program to start looking for the substring.
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6 using namespace std;
- 7
- 8 int main()
- 9 {
- 10 string word1 = "Game";
- 11 string word2("Over");
- 12 string word3(3, '!');
- 13
- 14 string phrase = word1 + " " + word2 + word3;
- 15 cout << "The phrase is: " << phrase << "\n";
- 16 cout << "The phrase has " << phrase.size() << " characters in it.\n";
- 17 cout << "The character at position 0 is: " << phrase[0] << "\n";
- 18 cout << "Changing the character at position 0.\n";
- 19 phrase[0] = 'L';
- 20 cout << "The phrase is now: " << phrase << "\n";
- 21 for (unsigned int i = 0; i < phrase.size(); ++i)
- 22 cout << "Character at position " << i << " is: " << phrase[i] << "\n";
- 23 cout << "The sequence 'Over' begins at location ";
- 24 cout << phrase.find("Over") << endl;
- 25 if (phrase.find("eggplant") == string::npos)
- 26 cout << "'eggplant' is not in the phrase.\n";
- 27 phrase.erase(4, 5);
- 28 cout << "The phrase is now: " << phrase << endl;
- 29 phrase.erase(4);
- 30 cout << "The phrase is now: " << phrase << endl;
- 31 phrase.erase();
- 32 cout << "The phrase is now: " << phrase << endl;
- 33 if (phrase.empty())
- 34 cout << "The phrase is no more.\n";
- 35 return 0;
- 36 }
wang@wang:~/test$ ./string_tester
The phrase is: Game Over!!!
The phrase has 12 characters in it.
The character at position 0 is: G
Changing the character at position 0.
The phrase is now: Lame Over!!!
Character at position 0 is: L
Character at position 1 is: a
Character at position 2 is: m
Character at position 3 is: e
Character at position 4 is:
Character at position 5 is: O
Character at position 6 is: v
Character at position 7 is: e
Character at position 8 is: r
Character at position 9 is: !
Character at position 10 is: !
Character at position 11 is: !
The sequence 'Over' begins at location 5
'eggplant' is not in the phrase.
The phrase is now: Lame!!!
The phrase is now: Lame
The phrase is now:
The phrase is no more.
(034) 英雄復仇遊戲
主要講述攜帶的裝備狀況
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6 using namespace std;
- 7
- 8 int main()
- 9 {
- 10 const int MAX_ITEMS = 10;
- 11 string inventory[MAX_ITEMS];
- 12 int numItems = 0;
- 13 inventory[numItems++] = "sword";
- 14 inventory[numItems++] = "armor";
- 15 inventory[numItems++] = "shield";
- 16 cout << "Your items:\n";
- 17 for (int i = 0; i < numItems; i++)
- 18 cout << inventory[i] << endl;
- 19 cout << "You trade your sword for a battle axe.\n";
- 20 inventory[0] = "battle axe";
- 21 for (int i = 0; i < numItems; ++i)
- 22 cout << inventory[i] << endl;
- 23 cout << "The item name '" << inventory[0] << "' has ";
- 24 cout << inventory[0].size() << " letters in it.\n";
- 25 cout << "You find a healing potion.\n";
- 26 if (numItems < MAX_ITEMS)
- 27 inventory[numItems++] = "healing portion";
- 28 else
- 29 cout << "You have too many items and can't carry another.\n";
- 30 for (int i = 0; i < numItems; ++i)
- 31 cout << inventory[i] << endl;
- 32 return 0;
- 33 }
wang@wang:~/test$ ./heros_inventory
Your items:
sword
armor
shield
You trade your sword for a battle axe.
battle axe
armor
shield
The item name 'battle axe' has 10 letters in it.
You find a healing potion.
battle axe
armor
shield
healing portion
(035) index check
Testing to make sure that an index number is a valid array position before using it is called bounds checking.
(036) tic-tac-toe遊戲
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 const int ROWS = 3;
- 10 const int COLUMNS = 3;
- 11 char board[ROWS][COLUMNS] = {{'O', 'X', 'O'}, {' ', 'X', 'X'}, {'X', 'O', 'O'}};
- 12 cout << "Here's the tic-tac-toe board:\n";
- 13 for (int i = 0; i < ROWS; i++) {
- 14 for (int j = 0; j < COLUMNS; ++j)
- 15 cout << board[i][j];
- 16 cout << endl;
- 17 }
- 18 cout << "'X' moves to the empty location.\n";
- 19 board[1][0] = 'X';
- 20 cout << "Now the tic-tac-toe board is:\n";
- 21 for (int i = 0; i < ROWS; i++) {
- 22 for(int j = 0; j < COLUMNS; ++j)
- 23 cout << board[i][j];
- 24 cout << endl;
- 25 }
- 26 cout << "'X' wins!\n";
- 27 return 0;
- 28 }
wang@wang:~/test$ ./tic-tac-toe_board
Here's the tic-tac-toe board:
OXO
XX
XOO
'X' moves to the empty location.
Now the tic-tac-toe board is:
OXO
XXX
XOO
'X' wins!
(037) 猜字遊戲
把單詞打亂,而後根據提示猜是什麼單詞。
-
-
- #include <iostream>
- #include <string>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
-
- int main()
- {
- enum field {WORD, HINT, NUM_FIELDS};
- const int NUM_WORDS = 5;
- const string WORDS[NUM_WORDS][NUM_FIELDS] = {
- {"wall", "Do you feel you're banging your head against something?"},
- {"glasses", "These might help you see the answer."},
- {"labored", "Going slowly, is it?"},
- {"persistent", "Keep at it."},
- {"jumble", "It's what the game is all about."}};
- srand(static_cast<unsigned int>(time(0)));
- int choice = rand() % NUM_WORDS;
- string theWord = WORDS[choice][WORD];
- string theHint = WORDS[choice][HINT];
-
- string jumble = theWord;
- int length = jumble.size();
- for (int i = 0; i < length; ++i) {
- int index1 = (rand() % length);
- int index2 = (rand() % length);
- char temp = jumble[index1];
- jumble[index1] = jumble[index2];
- jumble[index2] = temp;
- }
- cout << "\t\tWelcome to Word Jumble!\n";
- cout << "Unscramble the letters to make a word.\n";
- cout << "Enter 'hint' for a hint.\n";
- cout << "Enter 'quit' to quit the game.\n";
- cout << "The jumble is: " << jumble;
- string guess;
- cout << "\nyou guess: ";
- cin >> guess;
- while ((guess != theWord) && (guess != "quit")) {
- if(guess == "hint")
- cout << theHint;
- else
- cout << "Sorry, that's not it.";
- cout << "\nYour guess: ";
- cin >> guess;
- }
- if (guess == theWord)
- cout << "That's it! You guess it!\n";
- cout << "Thanks for playing.\n";
- return 0;
- }
wang@wang:~/test$ ./word_jumble
Welcome to Word Jumble!
Unscramble the letters to make a word.
Enter 'hint' for a hint.
Enter 'quit' to quit the game.
The jumble is: eetpsitsnr
you guess: hint
Keep at it.
Your guess: persistent
That's it! You guess it!
Thanks for playing.
(038) 對象
Objects are encapsulated, cohesive entities that combine data (called data members) and functions (called member functions).
(039) 習題
1. 增長計數的效果
- cin >> guess;
- 41 int count = 1;
- 42 while ((guess != theWord) && (guess != "quit")) {
- 43 if(guess == "hint")
- 44 cout << theHint;
- 45 else
- 46 cout << "Sorry, that's not it.";
- 47 cout << "\nYour guess: ";
- 48 cin >> guess;
- 49 ++count;
- 50 }
2. 數組訪問會越界
i < phrase.size();
3. char board[ROWS][COLUMNS];
Chapter 4: The Standard Template Library: Hangman
(040) 標準庫
The STL(Standard Template Library) represents a powerful collection of programming work that's been done well.
(041) 使用vector舉例
- 1 // Hero's Inventory 2.0
- 2 // Demonstrates vectors
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6 #include <vector>
- 7 using namespace std;
- 8
- 9 int main()
- 10 {
- 11 vector<string> inventory;
- 12 inventory.push_back("sword");
- 13 inventory.push_back("armor");
- 14 inventory.push_back("shield");
- 15 cout << "You have " << inventory.size() << " items.\n";
- 16 cout << "Your items:\n";
- 17 for (unsigned int i = 0; i < inventory.size(); ++i)
- 18 cout << inventory[i] << endl;
- 19 cout << "You trade your sword for a battle axe.";
- 20 inventory[0] = "battle axe";
- 21 cout << "Your items:\n";
- 22 for (unsigned int i = 0; i < inventory.size(); ++i)
- 23 cout << inventory[i] << endl;
- 24 cout << "The item name '" << inventory[0] << "' has ";
- 25 cout << inventory[0].size() << " letters in it.\n";
- 26 cout << "your shield is destroyed in a fierce battle.";
- 27 inventory.pop_back();
- 28 cout << "Your items:\n";
- 29 for (unsigned int i = 0; i < inventory.size(); ++i)
- 30 cout << inventory[i] << endl;
- 31 cout << "You were robbed of all of your possessions by a thief.\n";
- 32 inventory.clear();
- 33 if (inventory.empty())
- 34 cout << "You have nothing.\n";
- 35 else
- 36 cout << "You have at least one item.\n";
- 37 return 0;
- 38 }
wang@wang:~/workspace/beginc++game$ ./heros_inventory2
You have 3 items.
Your items:
sword
armor
shield
You trade your sword for a battle axe.Your items:
battle axe
armor
shield
The item name 'battle axe' has 10 letters in it.
your shield is destroyed in a fierce battle.Your items:
battle axe
armor
You were robbed of all of your possessions by a thief.
You have nothing.
(042) 迭代器舉例
- 1
- 2
- 3 #include <iostream>
- 4 #include <string>
- 5 #include <vector>
- 6 using namespace std;
- 7
- 8 int main()
- 9 {
- 10 vector<string> inventory;
- 11 inventory.push_back("sword");
- 12 inventory.push_back("armor");
- 13 inventory.push_back("shield");
- 14 vector<string>::iterator myIterator;
- 15 vector<string>::const_iterator iter;
- 16 cout << "Your items:\n";
- 17 for (iter = inventory.begin(); iter != inventory.end(); ++iter)
- 18 cout << *iter << endl;
- 19 cout << "You trade your sword for a battle axe.\n";
- 20 myIterator = inventory.begin();
- 21 *myIterator = "battle axe";
- 22 cout << "Your items:\n";
- 23 for (iter = inventory.begin(); iter != inventory.end(); ++iter)
- 24 cout << *iter << endl;
- 25 cout << "The item name '" << *myIterator << "' has ";
- 26 cout << (*myIterator).size() << " letters in it.\n";
- 27 cout << "The item name '" << *myIterator << "' has ";
- 28 cout << myIterator->size() << " letters in it.\n";
- 29 cout << "You recover a corssbox from a slain enemy.\n";
- 30 inventory.insert(inventory.begin(), "crossbox");
- 31 cout << "Your items:\n";
- 32 for (iter = inventory.begin(); iter != inventory.end(); ++iter)
- 33 cout << *iter << endl;
- 34 cout << "Your armor is destoryed in a fierce battle.\n";
- 35 inventory.erase(inventory.begin() + 2);
- 36 cout << "Your items:\n";
- 37 for (iter = inventory.begin(); iter != inventory.end(); ++iter)
- 38 cout << *iter << endl;
- 39 return 0;
- 40 }
wang@wang:~/test$ ./heros_inventory3
Your items:
sword
armor
shield
You trade your sword for a battle axe.
Your items:
battle axe
armor
shield
The item name 'battle axe' has 10 letters in it.
The item name 'battle axe' has 10 letters in it.
You recover a corssbox from a slain enemy.
Your items:
crossbox
battle axe
armor
shield
Your armor is destoryed in a fierce battle.
Your items:
crossbox
battle axe
shield
(043) insert方法
One form of the insert() member function inserts a new element into a vector just before the element referred to by a given iterator.
(044) 算法舉例
The random_shuffle() algorithm randomizes the elements of a sequence.
The sort() algorithm sorts the elements of a sequence in ascending order.
- 1
- 2
- 3 #include <iostream>
- 4 #include <vector>
- 5 #include <algorithm>
- 6 #include <ctime>
- 7 #include <cstdlib>
- 8 using namespace std;
- 9
- 10 int main()
- 11 {
- 12 vector<int>::const_iterator iter;
- 13 cout << "Creating a list of scores.\n";
- 14 vector<int> scores;
- 15 scores.push_back(1500);
- 16 scores.push_back(3500);
- 17 scores.push_back(7500);
- 18
- 19 cout << "High Scores:\n";
- 20 for (iter = scores.begin(); iter != scores.end(); ++iter)
- 21 cout << *iter << endl;
- 22 cout << "Finding a score:\n";
- 23 int score;
- 24 cout << "Enter a score to find: ";
- 25 cin >> score;
- 26 iter = find(scores.begin(), scores.end(), score);
- 27 if (iter != scores.end())
- 28 cout << "Score found.\n";
- 29 else
- 30 cout << "Score not found.\n";
- 31 cout << "Randomizing scores.\n";
- 32 srand(static_cast<unsigned int>(time(0)));
- 33 random_shuffle(scores.begin(), scores.end());
- 34 cout << "High Scores:\n";
- 35 for (iter = scores.begin(); iter != scores.end(); ++iter)
- 36 cout << *iter << endl;
- 37 cout << "Sorting scores.\n";
- 38 sort(scores.begin(), scores.end());
- 39 cout << "High Scores:\n";
- 40 for (iter = scores.begin(); iter != scores.end(); ++iter)
- 41 cout << *iter << endl;
- 42 return 0;
- 43 }
wang@wang:~/test$ ./high_scores
Creating a list of scores.
High Scores:
1500
3500
7500
Finding a score:
Enter a score to find: 7500
Score found.
Randomizing scores.
High Scores:
7500
3500
1500
Sorting scores.
High Scores:
1500
3500
7500
(045) 標註庫提供的全部容器
deque Sequential Double-ended queue
list Sequential Linear list
map Associative Collection of key/value pairs in which each key is associated with exactly one value
multimap Associative Collection of key/value pairs in which each key may be associated with more than one value
multiset Associative Collection in which each element is not necessarily unique
priority_queue Adaptor Priority queue
queue Adaptor Queue
set Associative Collection in which each element is unique
stack Adaptor Stack
vector Sequential Dynamic array
(046) Pseudocode僞代碼
須要很好的英語基礎。
Many programmers sketch out their programs using pseudocode - a language that falls somewhere between English and a formal programming language.
By taking each step described in pseudocode and breaking it down into series of simpler steps, the plan becomes closer to programming code.
(047) 僞代碼舉例
比較經典的例子,猜字遊戲,只有八次機會;
剛開始的時候能夠亂猜,後來根據已知的字符猜未知的字符。
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #include <iostream>
- #include <string>
- #include <vector>
- #include <algorithm>
- #include <ctime>
- #include <cctype>
-
- using namespace std;
-
- int main(int argc, char *argv[])
- {
-
-
- const int MAX_WRONG = 8;
- vector<string> words;
- words.push_back("GUESS");
- words.push_back("HANGMAN");
- words.push_back("DIFFICULT");
- srand(static_cast<unsigned int>(time(0)));
- random_shuffle(words.begin(), words.end());
- const string THE_WORD = words[0];
-
- int wrong = 0;
-
- string soFar(THE_WORD.size(), '-');
-
- string used = "";
-
- cout << "Welcome to Hangman. Good luck!\n";
-
-
- while ((wrong < MAX_WRONG) && (soFar != THE_WORD)) {
- cout << "You have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";
- cout << "You have used the following letters: " << used << endl;
- cout << "So far, the word is: " << soFar << endl;
- char guess;
- cout << "Enter your guess: ";
- cin >> guess;
-
- guess = toupper(guess);
- while (used.find(guess) != string::npos) {
- cout << "You have already guessed " << guess << endl;
- cout << "Enter your guess: ";
- cin >> guess;
- guess = toupper(guess);
- }
- used += guess;
- if (THE_WORD.find(guess) != string::npos) {
- cout << "That's right! " << guess << " is in the word.\n";
-
- for (int i = 0; i < THE_WORD.size(); ++i)
- if (THE_WORD[i] == guess)
- soFar[i] = guess;
- } else {
- cout << "Sorry, " << guess << " isn't in the word.\n";
- ++wrong;
- }
- }
-
- if (wrong == MAX_WRONG)
- cout << "You have been hanged!\n";
- else
- cout << "You guess it!\n";
- cout << "The word was " << THE_WORD << endl;
-
- return 0;
- }
Welcome to Hangman. Good luck!
You have 8 incorrect guesses left.
You have used the following letters:
So far, the word is: -------
Enter your guess: a
That's right! A is in the word.
You have 8 incorrect guesses left.
You have used the following letters: A
So far, the word is: -A---A-
Enter your guess: h
That's right! H is in the word.
You have 8 incorrect guesses left.
You have used the following letters: AH
So far, the word is: HA---A-
Enter your guess: n
That's right! N is in the word.
You have 8 incorrect guesses left.
You have used the following letters: AHN
So far, the word is: HAN--AN
Enter your guess: g
That's right! G is in the word.
You have 8 incorrect guesses left.
You have used the following letters: AHNG
So far, the word is: HANG-AN
Enter your guess: m
That's right! M is in the word.
You guess it!
The word was HANGMAN
(048) 習題
1. 編寫vector包括你喜歡的遊戲
- 1 #include <algorithm>
- 2 #include <iostream>
- 3 #include <vector>
- 4 using namespace std;
- 5
- 6 int main()
- 7 {
- 8 vector<string> games;
- 9 vector<string>::iterator iter;
- 10 games.push_back("war world");
- 11 games.push_back("person vender");
- 12 iter = games.begin();
- 13 games.insert(iter, "hello world");
- 14 for (iter = games.begin(); iter != games.end(); ++iter)
- 15 cout << *iter << endl;
- 16 return 0;
- 17 }
wang@wang:~/test$ ./list_game
hello world
war world
person vender
2. 每次都是調過一個數據,沒有每一個都遍歷
3. 僞代碼,寫得很差。
get some words and introduction about every word.
choose one word in random.
jumble the word.
guess the word
if word equal quit, exit the game
if word equal hint, give the word introduction
if guess equal the word
you success
Chapter 5: Functions: Mad Lib
(049) 函數簡單舉例
- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5
- 6
- 7 void instruction();
- 8
- 9 int main()
- 10 {
- 11 instruction();
- 12 return 0;
- 13 }
- 14
- 15
- 16 void instruction() {
- 17 cout << "Welcome to the most fun you've ever had with text!\n";
- 18 cout << "Here's how to play the game...\n";
- 19 }
wang@wang:~/test$ ./instructions
Welcome to the most fun you've ever had with text!
Here's how to play the game...
(050) 第二個例子,傳遞參數
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6 using namespace std;
- 7
- 8 char askYesNo1();
- 9 char askYesNo2(string question);
- 10
- 11 int main()
- 12 {
- 13 char answer1 = askYesNo1();
- 14 cout << "Thank you for answering: " << answer1 << "\n";
- 15 char answer2 = askYesNo2("Do you wish to save your game?");
- 16 cout << "Thanks for answering: " << answer2 << "\n";
- 17 return 0;
- 18 }
- 19
- 20 char askYesNo1() {
- 21 char response1;
- 22 do {
- 23 cout << "Please enter 'y' or 'n': ";
- 24 cin >> response1;
- 25 } while(response1 != 'y' && response1 != 'n');
- 26 return response1;
- 27 }
- 28
- 29 char askYesNo2(string question) {
- 30 char response2;
- 31 do {
- 32 cout << question << " (y/n): ";
- 33 cin >> response2;
- 34 } while (response2 != 'y' && response2 != 'n');
- 35 return response2;
- 36 }
wang@wang:~/test$ ./yes_or_no
Please enter 'y' or 'n': n
Thank you for answering: n
Do you wish to save your game? (y/n): y
Thanks for answering: y
(051) 不要作別人重複的工做
It's always a waste of time to reinvent the wheel.
Increased company productivity.
Improved software quality.
Improved software performance.
(052) 變量空間
Every time you use curly braces to create a block, you create a scope.
- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5 void func();
- 6 int main()
- 7 {
- 8
- 9 int var = 5;
- 10 cout << "In main() var is: " << var << "\n";
- 11 func();
- 12 cout << "Back in main() var is: " << var << endl;
- 13 {
- 14 cout << "In main() in a new scope var is: " << var << endl;
- 15 cout << "Creating new var in new scope.\n";
- 16
- 17 int var = 10;
- 18 cout << "In main() in a new scope var is: " << var << "\n";
- 19 }
- 20 cout << "At end of main() var created in new scope no longer exists.\n";
- 21 cout << "At end of main() var is: " << var << "\n";
- 22 return 0;
- 23 }
- 24
- 25 void func()
- 26 {
- 27 int var = -5;
- 28 cout << "In func() var is: " << var << "\n";
- 29 }
wang@wang:~/test$ ./scoping
In main() var is: 5
In func() var is: -5
Back in main() var is: 5
In main() in a new scope var is: 5
Creating new var in new scope.
In main() in a new scope var is: 10
At end of main() var created in new scope no longer exists.
At end of main() var is: 5
(053) 全局變量舉例
- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5
- 6 int glob = 10;
- 7 void access_global();
- 8 void hide_global();
- 9 void change_global();
- 10 int main()
- 11 {
- 12 cout << "In main() glob is: " << glob << "\n";
- 13 access_global();
- 14 hide_global();
- 15 cout << "In main() glob is: " << glob << endl;
- 16 change_global();
- 17 cout << "In main() glob is: " << glob << endl;
- 18 return 0;
- 19 }
- 20
- 21 void access_global() {
- 22 cout << "In access_global() glob is: " << glob << endl;
- 23 }
- 24
- 25 void hide_global() {
- 26
- 27 int glob = 0;
- 28 cout << "In hide_global() glob is: " << glob << endl;
- 29 }
- 30
- 31 void change_global() {
- 32 glob = -10;
- 33 cout << "In change_global() glob is: " << glob << "\n";
- 34 }
wang@wang:~/test$ ./global_reach
In main() glob is: 10
In access_global() glob is: 10
In hide_global() glob is: 0
In main() glob is: 10
In change_global() glob is: -10
In main() glob is: -10
(054) 常量全局變量
Unlike global variables, which can make your programs confusing, global constants -- constants that can be accessed from anywhere in your program -- can help make programs clearer.
(055) 默認參數
- 1
- 2
- 3 #include <iostream>
- 4 #include <string>
- 5 using namespace std;
- 6
- 7 int askNumber(int high, int low = 1);
- 8
- 9 int main()
- 10 {
- 11 int number = askNumber(5);
- 12 cout << "Thanks for entering: " << number << "\n";
- 13 number = askNumber(10, 5);
- 14 cout << "Thanks for entering: " << number << "\n";
- 15 return 0;
- 16 }
- 17
- 18 int askNumber(int high, int low) {
- 19 int num;
- 20 do {
- 21 cout << "Please enter a number (" << low << " - " << high << "): ";
- 22 cin >> num;
- 23 } while (num > high || num < low);
- 24 return num;
- 25 }
wang@wang:~/test$ ./give_me_a_number
Please enter a number (1 - 5): 3
Thanks for entering: 3
Please enter a number (5 - 10): 6
Thanks for entering: 6
(056) 重載函數
- 1
- 2
- 3 #include <iostream>
- 4 #include <string>
- 5 using namespace std;
- 6 int triple(int number);
- 7 string triple(string text);
- 8
- 9 int main()
- 10 {
- 11 cout << "Tripling 5: " << triple(5) << "\n";
- 12 cout << "Tripling 'gamer': " << triple("gamer") << "\n";
- 13 return 0;
- 14 }
- 15
- 16 int triple(int number) {
- 17 return (number * 3);
- 18 }
- 19
- 20 string triple(string text) {
- 21 return (text + text + text);
- 22 }
wang@wang:~/test$ ./triple
Tripling 5: 15
Tripling 'gamer': gamergamergamer
(057) 內聯函數
內聯函數和默認參數相反,默認參數是在生命中,內聯函數是在定義中。
- 1
- 2
- 3 #include <iostream>
- 4 int radiation(int health);
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int health = 80;
- 10 cout << "Your health is " << health << "\n";
- 11 health = radiation(health);
- 12 cout << "After radiation exposure your health is " << health << endl;
- 13 health = radiation(health);
- 14 cout << "After radiation exposure your health is " << health << endl;
- 15 health = radiation(health);
- 16 cout << "After radiation exposure your health is " << health << endl;
- 17 return 0;
- 18 }
- 19
- 20 inline int radiation(int health) {
- 21 return (health / 2);
- 22 }
wang@wang:~/test$ ./taking_damage
Your health is 80
After radiation exposure your health is 40
After radiation exposure your health is 20
After radiation exposure your health is 10
(058) 綜合舉例
-
-
- #include <iostream>
- #include <string>
- using namespace std;
- string askText(string prompt);
- int askNumber(string prompt);
- void tellStory(string name, string noun, int number, string bodyPart, string verb);
-
- int main()
- {
- cout << "Welcome to Mad Lib.\n";
- cout << "Answer the following questions to help create a new story.\n";
- string name = askText("Please enter a name: ");
- string noun = askText("Please enter a plural noun: ");
- int number = askNumber("Please enter a number: ");
- string bodyPart = askText("Please enter a body part: ");
- string verb = askText("Please enter a verb: ");
- tellStory(name, noun, number, bodyPart, verb);
- return 0;
- }
-
- string askText(string prompt)
- {
- string text;
- cout << prompt;
- cin >> text;
- return text;
- }
-
- int askNumber(string prompt)
- {
- int num;
- cout << prompt;
- cin >> num;
- return num;
- }
-
- void tellStory(string name, string noun, int number, string bodyPart, string verb)
- {
- cout << "Here's your story:\n";
- cout << "The famous explorer " << name;
- cout << " had nearly given up a life-long quest to find.\n";
- cout << "The Lost City of " << noun << " when one day, the " << noun;
- cout << " found the explorer.\n";
- cout << "Surrounded by " << number << " " << noun;
- cout << ", a tear came to " << name << "'s " << bodyPart << ".\n";
- cout << "After all this time, the quest was finally over. ";
- cout << "And then, then " << noun << endl;
- cout << "promptly devoured ";
- cout << name << ". ";
- cout << "The moral of the story? Be careful what you " << verb << " for.\n";
- }
wang@wang:~/test$ ./mad_lib
Welcome to Mad Lib.
Answer the following questions to help create a new story.
Please enter a name: wang
Please enter a plural noun: wang
Please enter a number: 4
Please enter a body part: head
Please enter a verb: do
Here's your story:
The famous explorer wang had nearly given up a life-long quest to find.
The Lost City of wang when one day, the wang found the explorer.
Surrounded by 4 wang, a tear came to wang's head.
After all this time, the quest was finally over. And then, then wang
promptly devoured wang. The moral of the story? Be careful what you dofor.
(059) 習題
1. 默認參數放在函數生命最後。
2. Two function, one for input, another for judge.
-
-
- #include <iostream>
- #include <string>
- #include <vector>
- #include <algorithm>
- #include <ctime>
- #include <cctype>
-
- using namespace std;
-
- char guesschar() {
- char guess;
- cout << "Enter your guess: ";
- cin >> guess;
-
- guess = toupper(guess);
- return guess;
- }
-
- bool include(char c, string word) {
- for (int i = 0; i < word.size(); ++i)
- if (c == word[i])
- return true;
- }
-
- int main(int argc, char *argv[])
- {
-
-
- const int MAX_WRONG = 8;
- vector<string> words;
- words.push_back("GUESS");
- words.push_back("HANGMAN");
- words.push_back("DIFFICULT");
- srand(static_cast<unsigned int>(time(0)));
- random_shuffle(words.begin(), words.end());
- const string THE_WORD = words[0];
-
- int wrong = 0;
-
- string soFar(THE_WORD.size(), '-');
-
- string used = "";
-
- cout << "Welcome to Hangman. Good luck!\n";
-
-
- while ((wrong < MAX_WRONG) && (soFar != THE_WORD)) {
- cout << "You have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";
- cout << "You have used the following letters: " << used << endl;
- cout << "So far, the word is: " << soFar << endl;
- char guess = guesschar();
- while (used.find(guess) != string::npos) {
- cout << "You have already guessed " << guess << endl;
- guess = getchar();
- }
- used += guess;
- if (include(guess, THE_WORD)) {
- cout << "That's right! " << guess << " is in the word.\n";
-
- for (int i = 0; i < THE_WORD.size(); ++i)
- if (THE_WORD[i] == guess)
- soFar[i] = guess;
- } else {
- cout << "Sorry, " << guess << " isn't in the word.\n";
- ++wrong;
- }
- }
-
- if (wrong == MAX_WRONG)
- cout << "You have been hanged!\n";
- else
- cout << "You guess it!\n";
- cout << "The word was " << THE_WORD << endl;
-
- return 0;
- }
Welcome to Hangman. Good luck!
You have 8 incorrect guesses left.
You have used the following letters:
So far, the word is: -----
Enter your guess: E
That's right! E is in the word.
You have 8 incorrect guesses left.
You have used the following letters: E
So far, the word is: --E--
Enter your guess: F
Sorry, F isn't in the word.
You have 7 incorrect guesses left.
You have used the following letters: EF
So far, the word is: --E--
Enter your guess: D
Sorry, D isn't in the word.
You have 6 incorrect guesses left.
You have used the following letters: EFD
So far, the word is: --E--
Enter your guess: S
That's right! S is in the word.
You have 6 incorrect guesses left.
You have used the following letters: EFDS
So far, the word is: --ESS
Enter your guess: G
That's right! G is in the word.
You have 6 incorrect guesses left.
You have used the following letters: EFDSG
So far, the word is: G-ESS
Enter your guess: E
You have already guessed E
Sorry,
isn't in the word.
You have 5 incorrect guesses left.
You have used the following letters: EFDSG
So far, the word is: G-ESS
Enter your guess: U
That's right! U is in the word.
You guess it!
The word was GUESS
Press <RETURN> to close this window...
3. default argument