You have learned
that variables of type 'char' can only hold one character. A collection of
characters, (as in a name, an address, or even a social security number),
is called a string. The programming language 'C' handled strings in a very
complex way and, while C++ did much to improve upon 'C' in other ways, it
did little for string handling. The idea seemed to be that, if one wanted
a string type, then it should be implemented as a C++ class. Indeed, many
C++ textbooks include a demonstration of such a class.
More recently, the C++ development community has seen a need for a
built-in string type and the standards committee has included one in the
draft standard. In Borland C++, to access this type, one includes the file
<cstring.h>. Once this has been done, one can declare strings, as
in:
string mySocialSecurityNumber;
One can then perform the usual set of operations on such a string
including input, output, assignment, and comparison. Here is a simple
program that demonstrates some of the basic features. // Demonstration of the string type included in Borland C++
// The string 'Fred' is assumed to be 'correct'.
// File stringdm.cpp
#include <iostream.h>
#include <cstring.h>
void main()
{ string name1;
string name2 = "Fred";
cout << "Please enter a string\n";
cout << "Enter 'quit' to exit\n";
cin >> name1;
while (name1 != "quit")
{
if (name1 == name2) // The two strings must match completely
// In this case, an uppercase 'F' must be entered
{ cout << "The correct name was entered\n\n";
}
else
{ cout << "The name " << name1 << " was entered\n\n";
}
cout << "Please enter a string\n";
cout << "Enter 'quit' to exit\n";
cin >> name1;
}
}
Section XIII
of "The Essentials of C" provides more information about the string class.
|