< Previous | Contents | Next >
The Yes or No program asks the user typical questions a gamer might have to answer. First, the program asks the user to indicate yes or no. Then the program gets more specific and asks whether the user wants to save his game. Again, the results of the program are not remarkable; it’s their implementation that’s interesting. Each question is posed by a different function that communicates with main(). Figure 5.2 shows a sample run of the program.
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 5 folder; the filename is yes_or_no.cpp.
156 Chapter 5 n Functions: Mad Lib
Figure 5.2
Each question is asked by a separate function, and information is passed between these functions and
main().
// Yes or No
// Demonstrates return values and parameters
#include <iostream> #include <string>
using namespace std; char askYesNo1();
char askYesNo2(string question);
int main()
{
char answer1 = askYesNo1();
cout << "Thanks for answering: " << answer1 << "\n\n";
char answer2 = askYesNo2("Do you wish to save your game?"); cout << "Thanks for answering: " << answer2 << "\n";
return 0;
}
Using Parameters and Return Values 157
char askYesNo1()
{
char response1; do
{
cout << "Please enter ’y’ or ’n’: "; cin >> response1;
} while (response1 != ’y’ && response1 != ’n’);
return response1;
char askYesNo2(string question)
{
char response2; do
{
cout << question << " (y/n): "; cin >> response2;
} while (response2 != ’y’ && response2 != ’n’);
return response2;
}