⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch03.htm

📁 C++ From Scratch: An Object-Oriented Approach is designed to walk novice programmers through the ana
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><HTML><HEAD><SCRIPT LANGUAGE="JavaScript"><!--function popUp(pPage) { var fullURL = document.location; var textURL = fullURL.toString(); var URLlen = textURL.length; var lenMinusPage = textURL.lastIndexOf("/"); lenMinusPage += 1; var fullPath = textURL.substring(0,lenMinusPage); popUpWin = window.open('','popWin','resizable=yes,scrollbars=no,width=525,height=394'); figDoc= popUpWin.document; zhtm= '<HTML><HEAD><TITLE>' + pPage + '</TITLE>'; zhtm += '</head>'; zhtm += '<BODY bgcolor="#FFFFFF">'; zhtm += '<IMG SRC="' + fullPath + pPage + '">'; zhtm += '<P><B>' + pPage + '</B>'; zhtm += '</BODY></HTML>'; window.popUpWin.document.write(zhtm); window.popUpWin.document.close(); // Johnny Jackson 4/28/98 }//-->                                                                </SCRIPT>	<META NAME="Author" Content="Steph Mineart">	<META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1">	<TITLE>C++ From Scratch -- Ch 3 -- Program Flow</TITLE><link rel="stylesheet" href="/includes/stylesheets/ebooks.css"></head><BODY TEXT="#000000" BGCOLOR="#FFFFFF"><CENTER><H1><IMG SRC="../button/que.gif" WIDTH="171" HEIGHT="66" ALIGN="BOTTOM" BORDER="0"><BR>C++ From Scratch</h1></CENTER><CENTER>  <P><A HREF="../index.htm"><IMG SRC="../button/contents.gif" WIDTH="128"HEIGHT="28" ALIGN="BOTTOM" ALT="Contents" BORDER="0"></A>   <HR></CENTER><H1 align="center"> 3</H1><H1 align="center">Program Flow</H1><ul>  <li><a href="#Heading1">In this Chapter</a>   <li><a href="#Heading2">Building Robustness</a>   <li><a href="#Heading3">What Are You Trying to Accomplish?</a>   <li><a href="#Heading4">Solving the Problem with Loops</a>     <ul>      <li><a href="#Heading5">Relational Operators</a>       <li><a href="#Heading6">Blocks and Compound Statements</a>       <li><a href="#Heading7">Logical Operators</a>       <li><a href="#Heading8">Short Circuit Evaluation</a>       <li><a href="#Heading9">Relational Precedence</a>       <li><a href="#Heading10">Putting It All Together</a>       <li><a href="#Heading11">do while</a>       <li><a href="#Heading12">Enumerated Constants</a>       <li><a href="#Heading13">Returning to the Code</a>       <li><a href="#Heading14">Getting a Boolean Answer from the User</a>       <li><a href="#Heading15">Equality Operator ==</a>       <li><a href="#Heading16"> else</a>       <li><a href="#Heading17">The Conditional (or ternary) Operator</a>       <li><a href="#Heading18">Putting It All Together</a>     </ul></ul><hr size=4><a name="_Toc450552529"></a><a name="_Toc450553965"></a><a name="_Toc440589230"></a><a name="_Toc441727686"></a><a name="_Toc448989104"></a> <h2> <a name="Heading1">In this Chapter</a></h2><ul>  <li>     <p> Building Robustness</p>  </li>  <p></p>  <li>     <p> What Are You Trying to Accomplish?</p>  </li>  <p></p>  <li>     <p> Solving the Problem with Loops</p>  </li>  <p></p>  <li>     <p> The <tt>if</tt> Statement</p>  </li></ul><p>This chapter takes a look at how programs progress, how loops are created,   and how programs branch based on user input and other conditions. <a name="_Toc448989106"></a><a name="_Toc450553966"></a></p><h2> <a name="Heading2">Building Robustness</a></h2><p>Listing 2.1 in Chapter 2, "Getting Started," is vulnerable to incorrect user   input. For example, what happens if the user asks for 35 letters or says, "Use   five letters in six positions without duplicates." This, of course, is impossible:   You can't put five letters into six positions without duplicating at least one   letter. How do you prevent the user from giving you bogus data?</p><p>A <i>robust program</i> is one that can handle any user input without crashing.   Writing highly robust code is difficult and complex. Therefore, we won't set   a goal of handling absolutely any bogus data, but we will attempt to deal with   a few highly predictable errors.</p><blockquote>  <hr>  <p> <b>Robust</b>--A program is robust when it can handle incorrect user input     or other unanticipated events without crashing.</p>  <hr></blockquote><p>Listing 3.1 illustrates a more complex version of the code you just considered.   Before it is discussed, take a look at it and see if you can make some guesses   about what it is doing.</p><h4> Listing 3.1[em]A More Complex Version of Decryptix!</h4><pre><tt>0:  #include &lt;iostream&gt;</tt><tt>1:  using namespace std;</tt><tt>2:  int main()</tt><tt>3:  {</tt><tt>4:    cout &lt;&lt; "Decryptix. Copyright 1999 Liberty";</tt><tt>5:    cout &lt;&lt; "Associates, Inc. Version 0.2\n\n" &lt;&lt; endl;</tt><tt>6:    cout &lt;&lt; "There are two ways to play Decryptix: either";</tt><tt>7:    cout &lt;&lt; "you can guess a pattern I create,\n";</tt><tt>8:    cout &lt;&lt; "or I can guess your pattern.\n\n";</tt><tt>9:    cout &lt;&lt; "If you are guessing, I will think of a pattern\n";</tt><tt>10:   cout &lt;&lt; "of letters (e.g., abcde).\n\n";</tt><tt>11:   cout &lt;&lt; "On each turn, you guess the pattern and I will\n";</tt><tt>12:   cout &lt;&lt; "tell you how many letters you got right, and how many\n";</tt><tt>13:   cout &lt;&lt; "of the correct letters were in the correct position.\n\n";</tt><tt>14:   cout &lt;&lt; "The goal is to decode the puzzle as quickly as\n";</tt><tt>15:   cout &lt;&lt; "possible. You control how many letters can be\n";</tt><tt>16:   cout &lt;&lt; "used and how many positions (e.g., 5 possible \n";</tt><tt>17:   cout &lt;&lt; "letters in 4 positions) as well as whether or not\n";</tt><tt>18:   cout &lt;&lt; "the pattern might contain duplicate \n";</tt><tt>19:   cout &lt;&lt; "letters (e.g., aabcd).\n\n";</tt><tt>20:   cout &lt;&lt; "If I'm guessing, you think of a pattern and score \n";</tt><tt>21:   cout &lt;&lt; "each of my answers.\n\n" &lt;&lt; endl;</tt><tt>22:  </tt><tt>23:  </tt><tt>24:    int round = 1;</tt><tt>25:    int howManyLetters = 0, howManyPositions = 0;</tt><tt>26:    bool duplicatesAllowed = false;</tt><tt>27:    bool valid = false;</tt><tt>28:  </tt><tt>29:    const int minLetters = 2;</tt><tt>30:    const int maxLetters = 10;</tt><tt>31:    const int minPositions = 3;</tt><tt>32:    const int maxPositions = 10;</tt><tt>33:  </tt><tt>34:  </tt><tt>35:    while ( ! valid )</tt><tt>36:    {</tt><tt>37:       while ( howManyLetters &lt; minLetters </tt><tt>38:          || howManyLetters &gt; maxLetters )</tt><tt>39:       {</tt><tt>40:          cout &lt;&lt; "How many letters? (";</tt><tt>41:          cout &lt;&lt; minLetters &lt;&lt; "-" &lt;&lt; maxLetters &lt;&lt; "): ";</tt><tt>42:          cin &gt;&gt; howManyLetters;</tt><tt>43:          if ( howManyLetters &lt; minLetters </tt><tt>44:             || howManyLetters &gt; maxLetters )</tt><tt>45:          {</tt><tt>46:             cout &lt;&lt; "please enter a number between "; </tt><tt>47:             cout &lt;&lt; minLetters &lt;&lt; " and " &lt;&lt; maxLetters &lt;&lt; endl;</tt><tt>48:          }</tt><tt>49:       }</tt><tt>50:  </tt><tt>51:       while ( howManyPositions &lt; minPositions </tt><tt>52:          || howManyPositions &gt; maxPositions )</tt><tt>53:       {</tt><tt>54:          cout &lt;&lt; "How many positions? (";</tt><tt>55:          cout &lt;&lt; minPositions &lt;&lt; "-" &lt;&lt; maxPositions &lt;&lt; "): ";</tt><tt>56:          cin &gt;&gt; howManyPositions;</tt><tt>57:          if ( howManyPositions &lt; minPositions </tt><tt>58:             || howManyPositions &gt; maxPositions )</tt><tt>59:          {</tt><tt>60:             cout &lt;&lt; "please enter a number between ";</tt><tt>61:             cout &lt;&lt; minPositions &lt;&lt;" and " &lt;&lt; maxPositions &lt;&lt; endl;</tt><tt>62:          }</tt><tt>63:       }</tt><tt>64:  </tt><tt>65:       char choice = ' ';</tt><tt>66:       while ( choice != 'y' &amp;&amp; choice != 'n' )</tt><tt>67:       {</tt><tt>68:          cout &lt;&lt; "Allow duplicates (y/n)? ";</tt><tt>69:          cin &gt;&gt; choice;</tt><tt>70:       }</tt><tt>71:  </tt><tt>72:       duplicatesAllowed = choice == 'y' ? true : false;</tt><tt>73:  </tt><tt>74:       if ( ! duplicatesAllowed </tt><tt>75:          &amp;&amp; howManyPositions &gt; howManyLetters )</tt><tt>76:       {</tt><tt>77:         cout &lt;&lt; "I can't put " &lt;&lt; howManyLetters;</tt><tt>78:         cout &lt;&lt; " letters in " &lt;&lt; howManyPositions;</tt><tt>79:         cout &lt;&lt; " positions without duplicates! Please try again.\n";</tt><tt>80:          howManyLetters = 0;</tt><tt>81:          howManyPositions = 0;</tt><tt>82:       }</tt><tt>83:       else</tt><tt>84:       valid = true;</tt><tt>85:    }</tt><tt>86:  </tt><tt>87:    return 0;</tt><tt>88:  }<a name="_Toc448989107"></a><a name="_Toc450553967"></a></tt></pre><h2> <a name="Heading3">What Are You Trying to Accomplish?</a></h2><p>Line 35 brings us to the first line of code after the initialization of the   local variables and constants. </p><p>The goal with this piece of code is to prompt the user for a series of pieces   of information. Specifically, you want to know how many letters he or she will   use (for example, five letters means <i>a, b, c, d, </i>and <i>e</i>), how many   positions (for example, three positions means there are three letters that are   actually used in the code), and whether you'll allow duplicates (can one letter   repeat?)</p><p>The problem is that the user might not give you valid information. For example,   the user might tell you to use four letters in five positions with no duplicates.   This, unfortunately, is not physically possible. You want to make sure that   you have reasonable choices before moving forward with the program.</p><blockquote>  <hr>  <p><strong>NOTE: </strong> Let me pause and point out that in a real commercial     program, it is not unusual for literally dozens--or even hundreds--of lines     of code to be devoted to catching and responding appropriately to bogus user     input. You will not endeavor to be quite that robust here, but you do want     to trap the obvious mistakes and ask the user to try again. <a name="_Toc448989108"></a><a name="_Toc450553968"></a></p>  <hr></blockquote><h2> <a name="Heading4">Solving the Problem with Loops</a></h2><p>The essential approach to solving this problem is to do some work (ask the   user for input), test a condition (determine whether the data makes sense),   and, if the condition fails, start over.</p><p>This is called a <i>loop</i>; C++ supports a number of different looping mechanisms.</p><blockquote>  <hr>  <p> <b>loop</b>--A section of code that repeats.</p>  <hr></blockquote><p>Remember that you've created two constant integers for the values you need:   <tt>minLetters</tt> and <tt>maxLetters</tt>. Because you initialized <tt>howManyLetters</tt>   to zero, when you start out, <u>howManyLetters</u> is of course less than <tt>minLetters</tt>,   assuming that <tt>minLetters</tt> is greater than zero.</p><p>You want to continue to prompt and then reprompt the user while <u>howManyLetters</u>   is either less than the minimum or more than the maximum. To do this, you'll   create a <tt>while</tt> loop.</p><p>The syntax for the <tt>while</tt> statement is as follows:</p><pre><tt>while ( <i>condition</i> )</tt><tt><i>statement</i>;</tt></pre><p><tt><i>condition</i></tt> is any C++ expression, and <tt><i>statement</i></tt>   is any valid C++ statement or block of statements. When <tt><i>condition</i></tt>   evaluates to <tt>true</tt>, <tt><i>statement</i></tt> executes, and then <tt><i>condition</i></tt>   is tested again. This continues until <tt><i>condition</i></tt> tests false,   at which time the <tt>while</tt> loop terminates and execution continues on   the first line following <tt><i>statement</i></tt>.</p><p>Your <tt>while</tt> statement might be</p><pre><tt>while ( howManyLetters &lt; minLetters )</tt><tt>{</tt><tt>     //...</tt><tt>}</tt></pre><blockquote>  <hr>  <p><strong>NOTE: </strong> The symbol</p>  <p> <tt> //...</tt></p>  <p> indicates that I've left out code that you're not considering at the moment.     <a name="_Toc441727706"></a><a name="_Toc448989109"></a></p>  <hr></blockquote><h3> <a name="Heading5">Relational Operators</a></h3><p><i>Relational operators</i> determine whether two numbers are equal, or whether   one is greater or less than the other. Every relational statement evaluates   to either <tt>true</tt> or <tt>false</tt>. </p><blockquote>  <hr>  <p> <b>Relational Operator</b>--A symbol (for example, <tt>&gt;</tt> or <tt>&lt;</tt>)     that is used to determine the relative size of two objects. Relational operators     evaluate to <tt>true</tt> or <tt>false</tt>.</p>  <hr></blockquote><p>If the integer variable <tt>howManyLetters</tt> has the value <tt>1</tt> and   the constant <tt>minLetters</tt> has the value <tt>2</tt>, the expression</p><pre><tt>howManyLetters &lt; minLetters</tt></pre><p>returns <tt>true</tt>.</p><p>A <tt>while</tt> loop continues while the expression is true, so if <tt>howManyLetters</tt>   is <tt>1</tt> and <tt>minLetters</tt> is <tt>2</tt>, the expression is true   and the <tt>while</tt> loop will in fact execute.</p><p>Note that I talk about a single statement executing. It is also possible to   execute a <i>block</i> (that is, a group) of statements. <a name="_Toc448989110"></a></p><h3> <a name="Heading6">Blocks and Compound Statements</a></h3><p>A statement can be a single line or it can be a block of code that is surrounded   by braces, which is treated as a single statement. Although every statement   in the block must end with a semicolon, the block itself does not end with a   semicolon.</p><p>The block of code itself can consist of any number of statements, but it is   treated as a single statement.</p><p>This enables you to run several statements as the execution of a single <tt>while</tt>   loop.</p><p>Not only can you test whether one variable is less than another, you can test   whether one is larger, or even whether they are the same.</p><p>There are six relational operators listed in Table 3.1, which also shows each   operator's use and some sample code.</p><h4> Table 3.1 Relational Operators </h4><table border>  <tr valign="TOP" align="left">     <td colspan=1 align="left">       <p><b>Name</b></p>    </td>    <td colspan=1 align="left">       <p><b>Operator</b></p>    </td>    <td colspan=1 align="left">       <p><b>Sample</b></p>    </td>    <td colspan=1 align="left">       <p><b>Evaluates</b></p>    </td>  </tr>  <tr valign="TOP" align="left">     <td colspan=1 align="left">       <p>Equals</p>    </td>    <td colspan=1 align="left">       <p><tt>==</tt></p>    </td>    <td colspan=1 align="left">       <p><tt>100 == 50; </tt></p>    </td>    <td colspan=1 align="left">       <p><tt>false</tt></p>    </td>  </tr>  <tr valign="TOP" align="left">     <td colspan=1 align="left"><br>    </td>    <td colspan=1 align="left"><br>    </td>    <td colspan=1 align="left">       <p><tt>50 == 50; </tt></p>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -