Section 2- Strings

3A.2.1 Declaring and Initializing Strings

We've seen strings briefly in the form of string literals.  These were phrases inside quotes that we wanted to display in output statements like:

cout << "The final value of someNumber: " << someNumber << endl;

The phrase "The final value of someNumber: " is a string literal, and someNumber is an int variable that holds a numeric value.  But can we have a string variable that holds a string value?  You bet.  We declare a string variable just as we would an int, except we use the word string instead of int:

string thxMom;

So far, so good.  But what about assigning a value to this string, thxMom?  This part is a little stickier because strings, unlike ints, are not primitive data.  The data type string is actually a class, a kind of data type that is more powerful and flexible than a primitive type like int.  Also, we usually call variables of classes, objects rather than variables, just to remind us that they hold a more sophisticated kind of data than variables of primitive types.

The good news is, C++ lets you treat string objects almost as though they are primitive data types.  So you can, in fact do the following:

thxMom = "Thanks, Mom!";

Once we have done  that, we can use the variable thxMom as a string object that contains the value "Thanks, Mom" stored in it. Actually, there is a shorter way to do this, and you are welcome to do so:

string thxMom = "Thanks, Mom!";
decorative postcard

3A.2.2 Using Strings in Programs

It is incredibly easy to use strings.  Here is a simple example.  You'll notice that we have a new #include statement that brings in the <string> class library, needed for strings.

#include <iostream>
#include <string>
using namespace std;

int main()
{
string str;

str = "Hello there.  C++ is easy.";
cout << str << endl;

return (0);
}

This, as you can imagine, sends the following to the console:

console output

I realize that we could have created the same effect with the single statement:

cout << "Hello, there.  C++ is easy!";

However, declaring a string variable instead of using a string literal, has some advantages as we shall see.