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

📄 ch21.htm

📁 vc的电子书
💻 HTM
📖 第 1 页 / 共 5 页
字号:
38:       cout << "\nDone." << endl;
39:     return 0;
<TT>40: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: String One:
String Two:
String Three:
Enter a long string: Now is the time for all...

String One: Now is the time for all...
String Two:
String Three: Now is the time for all...

String One: Now is the time for all...
String Two: Now is th_+||
String Three: Now is the time for all...

String One: Now is the time for all...
String Two: Now is th
String Three: Now is the time for all...

Done.
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On lines 6, 7, and 8, three
string buffers are declared. Note that <TT>stringTwo</TT> is declared to be only
10 characters, while the others are 80. All three are initialized to zero length
on lines 10 to 12 and are printed on lines 14 to 16.<BR>
<BR>
The user is prompted to enter a string, and that string is copied to string three
on line 20. Line 21 is commented out; copying this long string to <TT>stringTwo</TT>
caused a crash on my computer because it wrote into memory that was critical to the
program.</P>
<P>The standard function <TT>strcpy()</TT> starts copying at the address pointed
to by the first parameter (the array name), and it copies the entire string without
ensuring that you've allocated room for it!</P>
<P>The standard library offers a second, safer function, <TT>strncpy()</TT>, which
copies only a specified number of characters to the target string. The <TT>n</TT>
in the middle of the function name <TT>strncpy()</TT> stands for number. This is
a convention used throughout the standard libraries.</P>
<P>On line 27, the first nine characters of <TT>stringOne</TT> are copied to <TT>stringTwo</TT>
and the result is printed. Because <TT>strncpy()</TT> does not put a null at the
end of the copied string, the result is not what was intended. Note that <TT>strcpy()</TT>
does null-terminate the copied string, but <TT>strncpy()</TT> does not, just to keep
life interesting.</P>
<P>The null is added on line 33, and the strings are then printed a final time.
<H4 ALIGN="CENTER"><A NAME="Heading9"></A><FONT COLOR="#000077">strcat() and strncat()</FONT></H4>
<P>Related to <TT>strcpy()</TT> and <TT>strncpy()</TT> are the standard functions
<TT>strcat()</TT> and <TT>strncat()</TT>. The former concatenates one string to another;
that is, it appends the string it takes as its second parameter to the end of the
string it takes as its first parameter. <TT>strncat()</TT>, as you might expect,
appends the first <TT>n</TT> characters of one string to the other. Listing 21.4
illustrates their use.</P>

<P><A NAME="Heading10"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 21.4. Using
strcat() and strncat().</B></FONT>
<PRE><FONT COLOR="#0066FF">1:     #include &lt;iostream.h&gt;
2:     #include &lt;string.h&gt;
3:
4:
5:     int main()
6:     {
7:        char stringOne[255];
8:        char stringTwo[255];
9:
10:       stringOne[0]='\0';
11:       stringTwo[0]='\0';
12:
13:       cout &lt;&lt; &quot;Enter a  string: &quot;;
14:       cin.getline(stringOne,80);
15:
16:       cout &lt;&lt; &quot;Enter a second string: &quot;;
17:       cin.getline(stringTwo,80);
18:
19:       cout &lt;&lt; &quot;String One: &quot; &lt;&lt; stringOne &lt;&lt; endl;
20:       cout &lt;&lt; &quot;String Two: &quot; &lt;&lt; stringTwo &lt;&lt; endl;
21:
22:       strcat(stringOne,&quot; &quot;);
23:       strncat(stringOne,stringTwo,10);
24:
25:       cout &lt;&lt; &quot;String One: &quot; &lt;&lt; stringOne &lt;&lt; endl;
26:       cout &lt;&lt; &quot;String Two: &quot; &lt;&lt; stringTwo &lt;&lt; endl;
27:
28:     return 0;
<TT>29: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: Enter a string: Oh beautiful
Enter a second string: for spacious skies for amber waves of grain
String One: Oh beautiful
String Two: for spacious skies for amber waves of grain
String One: Oh beautiful for spacio
String 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 character
arrays are created, and the user is prompted for two strings, which are put into
the two arrays.<BR>
<BR>
A space is appended to <TT>stringOne</TT> on line 22, and on line 23, the first ten
characters of <TT>stringTwo</TT> are appended to <TT>stringOne</TT>. The result is
printed 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 those
used to find occurrences of various characters or &quot;tokens&quot; within a string.
If you need to find a comma or a particular word as it occurs in a string, look to
the 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 approximation
of 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 nine
integer 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), the
day of the year (0-365), and a Boolean value establishing whether daylight saving
time 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 to
a variable of this type. There are conversion routines to turn such a variable into
a <TT>tm</TT> data structure.</P>
<P>The standard library supplies the function <TT>time()</TT>, which takes a pointer
to 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 control
over 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 illustrates
these various time functions.</P>

<P><A NAME="Heading13"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 21.5. Using
ctime().</B></FONT>
<PRE><FONT COLOR="#0066FF">1:     #include &lt;time.h&gt;
2:     #include &lt;iostream.h&gt;
3:
4:     int main()
5:     {
6:        time_t currentTime;
7:
8:        // get and print the current time
9:        time (&amp;currentTime); // fill now with the current time
10:       cout &lt;&lt; &quot;It is now &quot; &lt;&lt; ctime(&amp;currentTime) &lt;&lt; endl;
11:
12:       struct tm * ptm= localtime(&amp;currentTime);
13:
14:       cout &lt;&lt; &quot;Today is &quot; &lt;&lt; ((ptm-&gt;tm_mon)+1) &lt;&lt; &quot;/&quot;;
15:       cout &lt;&lt; ptm-&gt;tm_mday &lt;&lt; &quot;/&quot;;
16:       cout &lt;&lt; ptm-&gt;tm_year &lt;&lt; endl;
17:
18:       cout &lt;&lt; &quot;\nDone.&quot;;
19:     return 0;
<TT>20: }</TT>
Output: It is now Mon Mar 31 13:50:10 1997

Today is 3/31/97

Done.
</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 variable
is 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 variable
is then passed to <TT>ctime()</TT>, which returns an ASCII string that is in turn
passed 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 a
pointer to a <TT>tm</TT> structure is returned, which is used to initialize the local
variable <TT>ptm</TT>. The member data of this structure is then accessed to print
the 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 did
not fit into the other libraries. It includes simple integer math functions, sorting
functions (including <TT>qsort()</TT>, one of the fastest sorts available), and text
conversions 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 ASCII
to integer conversion. <TT>atoi()</TT> takes a single argument: a pointer to a constant
character string. It returns an integer (as you might expect). Listing 21.6 illustrates
its use.</P>

<P><A NAME="Heading15"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 21.6. Using
atoi() and related functions.</B></FONT>
<PRE><FONT COLOR="#0066FF">1:     #include &lt;stdlib.h&gt;
2:     #include &lt;iostream.h&gt;
3:
4:     int main()
5:     {
6:        char buffer[80];
7:        cout &lt;&lt; &quot;Enter a number: &quot;;
8:        cin &gt;&gt; buffer;
9:
10:       int number;
11:       // number = buffer; compile error
12:       number = atoi(buffer);
13:       cout &lt;&lt; &quot;Here's the number: &quot; &lt;&lt; number &lt;&lt; endl;
14:
15:       // int sum = buffer + 5;
16:       int sum = atoi(buffer) + 5;
17:       cout &lt;&lt; &quot;Here's sum: &quot; &lt;&lt; sum &lt;&lt; endl;
18:     return 0;
<TT>19: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: Enter a number: 9
Here's the number: 9
Here's sum: 14
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On line 6 of this simple
program, an 80-character buffer is allocated, and on line 7 the user is prompted
for 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 11
the 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 the
text 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 attempt
is made to assign to it the result of adding the integer constant <TT>5</TT> to the
buffer. 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 a
quick and easy way to do so. The hard part of using <TT>qsort()</TT> is setting up
the structures to pass in.</P>
<P><TT>qsort()</TT> takes four arguments. The first is a pointer to the start of
the table to be sorted (an array name works just fine), the second is the number
of elements in the table, the third is the size of each element, and the fourth is
a pointer to a comparison function.</P>
<P>The comparison function must return an <TT>int</TT>, and must take as its parameters
two constant <TT>void</TT> pointers. <TT>void</TT> pointers aren't used very often
in C++, as they diminish the type checking, but they have the advantage that they
can 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 how
to use the standard <TT>qsort()</TT> function.</P>

<P><A NAME="Heading17"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 21.7. Using
qsort().</B></FONT>
<PRE><FONT COLOR="#0066FF">1:     /* qsort example */
2:
3:     #include &lt;iostream.h&gt;
4:     #include &lt;stdlib.h&gt;
5:
6:     // form of sort_function required by qsort
7:     int sortFunction( const void *intOne, const void *intTwo);
8:
9:     const int TableSize = 10;  // array size
10:
11:    int main(void)
12:    {
13:       int i,table[TableSize];
14:
15:       // fill the table with values
16:       for (i = 0; i&lt;TableSize; i++)
17:       {
18:          cout &lt;&lt; &quot;Enter a number: &quot;;
19:          cin &gt;&gt; table[i];
20:       }
21:       cout &lt;&lt; &quot;\n&quot;;
22:
23:       // sort the values
24:       qsort((void *)table, TableSize, sizeof(table[0]), sortFunction);
25:
26:       // print the results
27:       for (i = 0; i &lt; TableSize; i++)
28:          cout &lt;&lt; &quot;Table [&quot; &lt;&lt; i &lt;&lt; &quot;]: &quot; &lt;&lt; table[i] &lt;&lt; endl;
29:
30:       cout &lt;&lt; &quot;Done.&quot; &lt;&lt; endl;

⌨️ 快捷键说明

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