The string library

Reading: Ch. 3.8

When discussing common data types we briefly mentioned the type string. What sets this data type apart from the other common types (e.g. int, double, char) is that the string type is not a part of the language's core (i.e, not a "primitive" data type).

Instead it is an example of a class which happens to have been defined in one of the standard C++ libraries. Therefore, when we wish to use it we must preface our code with the directive:

#include <string>
We will look at this class as our first example of object-oriented programming.

Let me stress that these notes are meant as a very coarse outline; please refer to the text for more explanation.


A string object has a set of attributes or data members (for representing the state of the object), yet it also supports a set of actions or member functions. We will look at several examples of the actions supported by this class. For each, we will focus on the transfer of information which takes places in such a method call, namely in the parameters sent to the method, and in the return value sent back as a result.

We will see how to invoke such methods on a particular string object, as in sample code.

Several operators have been defined to deal with string data as well, most notably:

A further note about reading strings from input. When using the >> operator, such as in

cin >> name;
any form of whitespace in the input is used as a delimiter. Thus if the user types in
Saint Louis University
in the above example, the variable name will be set equal to the string "Saint" as opposed to "Saint Louis University". If the desire is to read in an entire line of input into a single stream, the library provides an auxiliary function called getline which has the following signature:
getline(istream streamName, string result)
getline(istream streamName, string result, char delim)


Last modified: Wednesday, 20 April 2005