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

📄 tut3-2.html

📁 a Complete C++ language tutorial on the cplusplus.com
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<html>
<head>
<title>C++ Tutorial: 3.2, Strings of Characters.</title>
<META NAME="description" CONTENT="Declaration, initialization and use of strings. Standard Input with strings using cin.getline.">
<META NAME="keywords" CONTENT="cin.getline atol atoi buffer">
</head>

<body bgcolor="white">

<!--captut-->
<CENTER>
<TABLE WIDTH=100% CELLPADDING=0 CELLSPACING=1 BORDER=0>
<TR><TD WIDTH=90%>
 <FONT SIZE=4> Section 3.2 </FONT><BR>
 <FONT SIZE=5><B> Strings of Characters.</B></FONT>
</TD><TD><!--ad--><!--#include virtual="/ad/ad468.shtml"--><!--/ad-->
</TD><TD VALIGN="bottom"><A HREF="http://www.cplusplus.com/doc/tutorial/">
 <IMG SRC="head.gif" ALT="cplusplus.com" BORDER=0></A></TD></TR>
<TR><TD BGCOLOR="#0000FF" ALIGN="center" COLSPAN=3>
 <IMG SRC="head0.gif" WIDTH=2 HEIGHT=2 BORDER=0></TD></TR>
</TABLE>
</CENTER>
<!--/captut-->

<p>
In all programs seen until now, we have used only numerical variables,
used to express numbers exclusively. But in addition to numerical variables there also
exist strings of characters, that allow us to represent successions of characters,
like words, sentences, names, texts, et cetera. Until now we have only used them
as constants, but we have never considered variables able to contain them.
<p>
In C++ there is no specific <I>elemental</I> variable type to store strings of characters.
In order to fulfill this feature we can use arrays of type <tt><b>char</b></tt>,
which are successions of <tt><b>char</b></tt> elements. Remember that this data type
(<tt><b>char</b></tt>) is the one used to store a single character, for that reason arrays
of them are generally used to make strings of single characters.
<p>
For example, the following array (or string of characters):
<blockquote><tt><b>char jenny [20];</b></tt><br></blockquote>
can store a string up to 20 characters long. You may imagine it thus:
<blockquote><img src="imgstri1.gif"></blockquote>
This maximum size of 20 characters is not required to always be fully used. For example,
<tt><b>jenny</b></tt> could store at some moment in a program either the string of characters 
<tt>"Hello"</tt> or the string <tt>"Merry christmas"</tt>.  Therefore, since the array
of characters can store shorter strings than its total length, a convention has been
reached to end the valid content of a string with a null character, whose
constant can be written <TT><B>0</B></TT> or <TT><B>'\0'</B></tt>.
<p>
We could represent <tt><b>jenny</b></tt> (an array of 20 elements of type
<tt><b>char</b></tt>) storing the strings of characters <tt>"Hello"</tt> and
<tt>"Merry Christmas"</tt> in the following way:

<blockquote><img src="imgstri2.gif"></blockquote>

Notice how after the valid content a null character (<tt><b>'\0'</b></tt>) 
it is included in order to indicate the end of the string. The panels in gray color represent indeterminate
values.

<p>
<h2>Initialization of strings</h2>
<p>
Because strings of characters are ordinary arrays they fulfill all their same rules.
For example, if we want to initialize a string of characters with predetermined
values we can do it just like any other array:
<blockquote><tt>
char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
</tt></blockquote>

In this case we would have declared a string of characters (array) of 6 elements of
type <tt><b>char</b></tt> initialized with the characters that compose
<tt><b>Hello</b></tt> plus a null character <tt><b>'\0'</b></tt>.

<p>
Nevertheless, strings of characters have an additional way to initialize their values:
using <u>constant strings</u>.

<p>
In the expressions we have used in examples in previous chapters <U>constants</U> 
that represented entire strings of characters have already appeared several times.
These are specified enclosed between double quotes (<tt>"</tt>), for example:<br>
<blockquote><tt>"the result is: "</tt></blockquote>
is a constant string that we have probably used on some occasion.
<p>
Unlike single quotes (<tt>'</tt>) which specify single character constants,
double quotes (<tt>"</tt>) are constants that specify a succession of characters.
Strings enclosed between double quotes always have a 
null character (<tt>'\0'</tt>) automatically appended at the end.
<p>
Therefore we could initialize the string <tt><b>mystring</b></tt> with values by
either of these two ways:
<blockquote>
<tt>char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };</tt><br>
<tt>char mystring [] = "Hello";</tt>
</blockquote>
In both cases the array or string of characters <tt><b>mystring</b></tt> is declared
with a size of 6 characters (elements of type <tt><b>char</b></tt>): the 5 characters
that compose <tt><b>Hello</b></tt> plus a final null character (<tt>'\0'</tt>) which 
specifies the end of the string and that, in the second case, when using double quotes
(<tt><b>"</b></tt>) it is automatically appended.
<p>
Before going further, notice that the assignation of multiple constants like
double-quoted constants (<tt>"</tt>) to arrays are only valid when
<u>initializing</u> the array, that is, at the moment when declared.
Expressions within the code like:<br>
<blockquote><tt><font color="red">
mystring = "Hello";<br>
mystring[] = "Hello";
</font></tt></blockquote>
are not valid for arrays, like neither would be:<br>
<blockquote><tt><font color="red">
mystring = { 'H', 'e', 'l', 'l', 'o', '\0' };<br>
</font></tt></blockquote>
So remember: <u>We can "assign" a multiple constant to an Array only at the moment of
initializing it</u>. The reason will be more comprehensible when you know a bit more
about pointers, since then it will be clarified that an array is simply a <I>constant
pointer</I> pointing to an allocated block of memory. And because of this constantnes,
the array itself can not be assigned any value, but we can assing values to each of the
elements of the array.
<P>
The moment of initializing an Array it is a special case, since it is not an
assignation, although the same equal sign (<TT><B>=</B></TT>) is used.
Anyway, always have the rule previously underlined present.
<p>
<H2>Assigning values to strings</H2>
Since the <i>lvalue</i> of an assignation can only be an element of an array
and not the entire array, it would be valid to assign a string of characters to
an array of <tt><b>char</b></tt> using a method like this:<br>
<blockquote>
<tt><b>mystring[0] = 'H';<br>
mystring[1] = 'e';<br>
mystring[2] = 'l';<br>
mystring[3] = 'l';<br>
mystring[4] = 'o';<br>
mystring[5] = '\0';</b></tt><br>
</blockquote>
But as you may think, this does not seem to be a very practical method.  Generally for
assigning values to an array, and more specifically to a string of characters, a series
of functions like <tt><b>strcpy</b></tt> are used. 
<B>strcpy</B> (<b>str</b>ing <b>c</b>o<b>py</b>) is defined in
the <tt><b>cstring</b></tt> (<TT>string.h</TT>) library and can be called
the following way:<br>
<blockquote>
<tt><b>strcpy (</b><i>string1</i><b>, </b><i>string2</i><b>);</b></tt><br>
</blockquote>
This does copy the content of <tt><i>string2</i></tt> into <tt><i>string1</i></tt>.
<TT><I>string2</I></TT> can be either an array, a pointer, or a <U>constant string</U>,
so the following line would be a valid way to assign the constant string
<tt><b>"Hello"</b></tt> to <tt><b>mystring</b></tt>:<br>
<blockquote><tt>strcpy (mystring, "Hello");</tt><br></blockquote>

For example:
<P><CENTER>
<TABLE WIDTH=100% CELLPADDING=5 CELLSPACING=5><TR><TD BGCOLOR="#FFFFBF" WIDTH=50% VALIGN="top">
<TT><PRE><I>// setting value to string</I>
#include &lt;iostream.h&gt;
#include &lt;string.h&gt;

int main ()
{
  char szMyName [20];
  strcpy (szMyName,"J. Soulie");
  cout &lt;&lt; szMyName;
  return 0;
}
</PRE></TT>
</TD><TD BGCOLOR="silver" WIDTH=50% VALIGN="top">
<B><TT>J. Soulie</TT></B>
</TD></TR></TABLE>
</CENTER>
<P>
Notice that we needed to include <TT><B>&lt;string.h&gt;</B></TT> header
in order to be able to use function <TT><B>strcpy</B></TT>.

<p>
Although we can always write a simple function like the following <tt><b>setstring</b></tt>
with the same operation as cstring's <tt><b>strcpy</b></tt>:

<P><CENTER>
<TABLE WIDTH=100% CELLPADDING=5 CELLSPACING=5><TR><TD BGCOLOR="#FFFFBF" WIDTH=50% VALIGN="top">
<TT><PRE><I>// setting value to string</I>
#include &lt;iostream.h&gt;

void setstring (char szOut [], char szIn [])
{
  int n=0;

⌨️ 快捷键说明

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