📄 ch21.htm
字号:
14: cin.getline(stringOne,80);15:16: cout << "Enter a second string: ";17: cin.getline(stringTwo,80);18:19: cout << "String One: " << stringOne << endl;20: cout << "String Two: " << stringTwo << endl;21:22: strcat(stringOne," ");23: strncat(stringOne,stringTwo,10);24:25: cout << "String One: " << stringOne << endl;26: cout << "String Two: " << stringTwo << endl;27:28: return 0;<TT>29: }</TT></FONT><FONT COLOR="#0066FF">Output: Enter a string: Oh beautifulEnter a second string: for spacious skies for amber waves of grainString One: Oh beautifulString Two: for spacious skies for amber waves of grainString One: Oh beautiful for spacioString Two: for spacious skies for amber waves of grain</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On lines 7 and 8, two characterarrays are created, and the user is prompted for two strings, which are put intothe two arrays.<BR><BR>A space is appended to <TT>stringOne</TT> on line 22, and on line 23, the first tencharacters of <TT>stringTwo</TT> are appended to <TT>stringOne</TT>. The result isprinted on lines 25 and 26.<H4 ALIGN="CENTER"><A NAME="Heading11"></A><FONT COLOR="#000077">Other String Functions</FONT></H4><P>The string library provides a number of other string functions, including thoseused to find occurrences of various characters or "tokens" within a string.If you need to find a comma or a particular word as it occurs in a string, look tothe string library to see whether the function you need already exists.<H3 ALIGN="CENTER"><A NAME="Heading12"></A><FONT COLOR="#000077">Time and Date</FONT></H3><P>The time library provides a number of functions for obtaining a close approximationof the current time and date, and for comparing times and dates to one another.</P><P>The center of this library is a structure, <TT>tm</TT>, which consists of nineinteger values for the second, minute, hour, day of the month, number of the month(where January=0), the number of years since 1900, the day (where Sunday=0), theday of the year (0-365), and a Boolean value establishing whether daylight savingtime is in effect. (This last may not be supported on some systems.)</P><P>Most time functions expect a variable of type <TT>time_t</TT> or a pointer toa variable of this type. There are conversion routines to turn such a variable intoa <TT>tm</TT> data structure.</P><P>The standard library supplies the function <TT>time()</TT>, which takes a pointerto a <TT>time_t</TT> variable and fills it with the current time. It also provides<TT>ctime()</TT>, which takes the <TT>time_t</TT> variable filled by <TT>time()</TT>and returns an ASCII string that can be used for printing. If you need more controlover the output, however, you can pass the <TT>time_t</TT> variable to <TT>local_time()</TT>,which will return a pointer to a <TT>tm</TT> structure. Listing 21.5 illustratesthese various time functions.</P><P><A NAME="Heading13"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 21.5. Usingctime().</B></FONT><PRE><FONT COLOR="#0066FF">1: #include <time.h>2: #include <iostream.h>3:4: int main()5: {6: time_t currentTime;7:8: // get and print the current time9: time (&currentTime); // fill now with the current time10: cout << "It is now " << ctime(&currentTime) << endl;11:12: struct tm * ptm= localtime(&currentTime);13:14: cout << "Today is " << ((ptm->tm_mon)+1) << "/";15: cout << ptm->tm_mday << "/";16: cout << ptm->tm_year << endl;17:18: cout << "\nDone.";19: return 0;<TT>20: }</TT>Output: It is now Mon Mar 31 13:50:10 1997Today is 3/31/97Done.</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On line 6, <TT>CurrentTime</TT>is declared to be a variable of type <TT>time_t</TT>. The address of this variableis passed to the standard time library function <TT>time()</TT>, and the variable<TT>currentTime</TT> is set to the current date and time. The address of this variableis then passed to <TT>ctime()</TT>, which returns an ASCII string that is in turnpassed to the <TT>cout</TT> statement on line 12.The address of <TT>currentTime</TT>is then passed to the standard time library function <TT>localtime()</TT>, and apointer to a <TT>tm</TT> structure is returned, which is used to initialize the localvariable <TT>ptm</TT>. The member data of this structure is then accessed to printthe current month, day of the month, and year. <H3 ALIGN="CENTER"><A NAME="Heading14"></A><FONT COLOR="#000077">stdlib</FONT></H3><P><TT>stdlib</TT> is something of a miscellaneous collection of functions that didnot fit into the other libraries. It includes simple integer math functions, sortingfunctions (including <TT>qsort()</TT>, one of the fastest sorts available), and textconversions for moving from ASCII text to integers, <TT>long</TT>, <TT>float</TT>,and so forth.</P><P>The functions in <TT>stdlib</TT> you are likely to use most often include <TT>atoi()</TT>,<TT>itoa()</TT>, and the family of related functions. <TT>atoi()</TT> provides ASCIIto integer conversion. <TT>atoi()</TT> takes a single argument: a pointer to a constantcharacter string. It returns an integer (as you might expect). Listing 21.6 illustratesits use.</P><P><A NAME="Heading15"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 21.6. Usingatoi() and related functions.</B></FONT><PRE><FONT COLOR="#0066FF">1: #include <stdlib.h>2: #include <iostream.h>3:4: int main()5: {6: char buffer[80];7: cout << "Enter a number: ";8: cin >> buffer;9:10: int number;11: // number = buffer; compile error12: number = atoi(buffer);13: cout << "Here's the number: " << number << endl;14:15: // int sum = buffer + 5;16: int sum = atoi(buffer) + 5;17: cout << "Here's sum: " << sum << endl;18: return 0;<TT>19: }</TT></FONT><FONT COLOR="#0066FF">Output: Enter a number: 9Here's the number: 9Here's sum: 14</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On line 6 of this simpleprogram, an 80-character buffer is allocated, and on line 7 the user is promptedfor a number. The input is taken as text and written into the buffer.<BR>On line 10, an <TT>int</TT> variable, <TT>number</TT>, is declared, and on line 11the program attempts to assign the contents of the buffer to the <TT>int</TT> variable.This generates a compile-time error and is commented out.</P><P>On line 12, the problem is solved by invoking the standard library function <TT>atoi()</TT>,passing in the buffer as the parameter. The return value, the integer value of thetext string, is assigned to the integer variable number and printed on line 13.</P><P>On line 15, a new integer variable, <TT>sum</TT>, is declared, and an attemptis made to assign to it the result of adding the integer constant <TT>5</TT> to thebuffer. This, too, fails and is solved by calling the standard function <TT>atoi()</TT>.<BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Some compilers implement standard conversion procedures (such as <TT>atoi()</TT>) using macros. You can usually use these functions without worrying about how they are implemented. Check your compiler's documentation for details. <HR></BLOCKQUOTE><H4 ALIGN="CENTER"><A NAME="Heading16"></A><FONT COLOR="#000077">qsort()</FONT></H4><P>At times you may want to sort a table or an array; <TT>qsort()</TT> provides aquick and easy way to do so. The hard part of using <TT>qsort()</TT> is setting upthe structures to pass in.</P><P><TT>qsort()</TT> takes four arguments. The first is a pointer to the start ofthe table to be sorted (an array name works just fine), the second is the numberof elements in the table, the third is the size of each element, and the fourth isa pointer to a comparison function.</P><P>The comparison function must return an <TT>int</TT>, and must take as its parameterstwo constant <TT>void</TT> pointers. <TT>void</TT> pointers aren't used very oftenin C++, as they diminish the type checking, but they have the advantage that theycan be used to point to items of any type. If you were writing your own <TT>qsort()</TT>function, you might consider using templates instead. Listing 21.7 illustrates howto use the standard <TT>qsort()</TT> function.</P><P><A NAME="Heading17"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 21.7. Usingqsort().</B></FONT><PRE><FONT COLOR="#0066FF">1: /* qsort example */2:3: #include <iostream.h>4: #include <stdlib.h>5:6: // form of sort_function required by qsort7: int sortFunction( const void *intOne, const void *intTwo);8:9: const int TableSize = 10; // array size10:11: int main(void)12: {13: int i,table[TableSize];14:15: // fill the table with values16: for (i = 0; i<TableSize; i++)17: {18: cout << "Enter a number: ";19: cin >> table[i];20: }21: cout << "\n";22:23: // sort the values24: qsort((void *)table, TableSize, sizeof(table[0]), sortFunction);25:26: // print the results27: for (i = 0; i < TableSize; i++)28: cout << "Table [" << i << "]: " << table[i] << endl;29:30: cout << "Done." << endl;31: return 0;32: }33:34: int sortFunction( const void *a, const void *b)35: {36: int intOne = *((int*)a);37: int intTwo = *((int*)b);38: if (intOne < intTwo)39: return -1;40: if (intOne == intTwo)41: return 0;42: return 1;<TT>43: }</TT>Output: Enter a number: 2Enter a number: 9Enter a number: 12Enter a number: 873Enter a number: 0Enter a number: 45Enter a number: 93Enter a number: 2Enter a number: 66Enter a number: 1Table[0]: 0Table[1]: 1Table[2]: 2Table[3]: 2Table[4]: 9Table[5]: 12Table[6]: 45Table[7]: 66Table[8]: 93Table[9]: 873Done.</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On line 4, the standard libraryheader is included, which is required by the <TT>qsort()</TT> function. On line 7,the function <TT>sortFunction()</TT> is declared, which takes the required four parameters.<BR><BR>An array is declared on line 13 and filled by user input on lines 16-20. <TT>qsort()</TT>is called on line 24, casting the address of the array name <TT>table</TT> to bea <TT>void*</TT>.</P><P>Note that the parameters for <TT>sortFunction</TT> are not passed to the callto <TT>qsort()</TT>. The name of the <TT>sortFunction</TT>, which is itself a pointerto that function, is the parameter to <TT>qsort()</TT>.</P><P>Once <TT>qsort()</TT> is running, it will fill the constant <TT>void</TT> pointers<TT>a</TT> and <TT>b</TT> with each value of the array. If the first value is smallerthan the second, the comparison function must return <TT>-1</TT>. If it is equal,the comparison function must return <TT>0</TT>. Finally, if the first value is greaterthan the second value, the comparison function must return <TT>1</TT>. This is reflectedin the <TT>sortFunction()</TT>, as shown on lines 34 to 43.<H4 ALIGN="CENTER"><A NAME="Heading18"></A><FONT COLOR="#000077">Other Libraries</FONT></H4><P>Your C++ compiler supplies a number of other libraries, among them the standardinput and output libraries and the stream libraries that you've been using throughoutthis book. It is well worth your time and effort to explore the documentation thatcame with your compiler to find out what these libraries have to offer.<H3 ALIGN="CENTER"><A NAME="Heading19"></A><FONT COLOR="#000077">Bit Twiddling</FONT></H3><P>Often you will want to set flags in your objects to keep track of the state ofyour object. (Is it in <TT>AlarmState</TT>? Has this been initialized yet? Are youcoming or going?)</P><P>You can do this with user-defined Booleans, but when you have many flags, andwhen storage size is an issue, it is convenient to be able to use the individualbits as flags.</P><P>Each byte has eight bits, so in a four-byte <TT>long</TT> you can hold 32 separateflags. A bit is said to be "set" if its value is <TT>1</TT>, and clearif its value is <TT>0</TT>. When you set a bit, you make its value <TT>1</TT>, andwhen you clear it, you make its value <TT>0</TT>. (Set and clear are both adjectivesand verbs). You can set and clear bits by changing the value of the <TT>long</TT>,but that can be tedious and confusing.<BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Appendix C, "Binary and Hexadecimal," provides valuable additional information about binary and hexadecimal manipulation. <HR></BLOCKQUOTE><P>C++ provides bitwise operators that act upon the individual bits.These look like,but are different from, the logical operators, so many novice programmers confusethem. The bitwise operators are presented in Table 21.1. <BR><BR><FONT SIZE="4"><B>Table 21.1. The Bitwise Operators. </B></FONT><TABLE BORDER="0" WIDTH="145"> <TR ALIGN="LEFT" rowspan="1"> <TD WIDTH="64" ALIGN="LEFT"><B><I>symbol</I></B></TD> <TD ALIGN="LEFT"><B><I>operator</I></B></TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD WIDTH="64" ALIGN="LEFT"><TT>&</TT></TD> <TD ALIGN="LEFT"><TT>AND</TT></TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD WIDTH="64" ALIGN="LEFT"><TT>|</TT></TD> <TD ALIGN="LEFT"><TT>OR</TT></TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD WIDTH="64" ALIGN="LEFT"><TT>^</TT></TD> <TD ALIGN="LEFT">exclusive <TT>OR</TT></TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD WIDTH="64" ALIGN="LEFT"><TT>~</TT></TD> <TD ALIGN="LEFT">complement</TD> </TR></TABLE><CENTER><H4><A NAME="Heading20"></A><FONT COLOR="#000077">Operator AND</FONT></H4></CENTER><P>The <TT>AND</TT> operator (<TT>&</TT>) is a single ampersand, as opposed tothe logical <TT>AND</TT>, which is two ampersands. When you <TT>AND</TT> two bits,the result is <TT>1</TT> if both bits are <TT>1</TT>, but <TT>0</TT> if either orboth bits are <TT>0</TT>. The way to think of this is: The result is <TT>1</TT> ifbit 1 is set and if bit 2 is set.<CENTER><H4><A NAME="Heading21"></A><FONT COLOR="#000077">Operator OR</FONT></H4></CENTER><P>The second bitwise operator is <TT>OR</TT> (<TT>|</TT>). Again, this is a singlevertical bar, as opposed to the logical <TT>OR</TT>, which is two vertical bars.When you <TT>OR</TT> two bits, the result is <TT>1</TT> if either bit is set or ifboth are.<CENTER><H4><A NAME="Heading22"></A><FONT COLOR="#000077">Operator Exclusive OR</FONT></H4></CENTER><P>The third bitwise operator is exclusive <TT>OR</TT> (<TT>^</TT>). When you exclusive<TT>OR</TT> two bits, the result is <TT>1</TT> if the two bits are different.<CENTER><H4><A NAME="Heading23"></A><FONT COLOR="#000077">The Complement Operator</FONT></H4></CENTER><P>The complement operator (<TT>~</TT>) clears every bit in a number that is setand sets every bit that is clear. If the current value of the number is <TT>1010
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -