CS 1440 Lab 6

Cover sheetPrevious ActivityNext Activity

Activity 6-2: New Data Types

Activity Goals

Activity Procedure

While the char C++ base data type is not new to you, we haven’t really used or discussed it much.  That’s about to change!  A new data type is the string.  To use this new data type you must have the following statement in your program.

#include  <string>

A string is a collection of characters.  The string data type is not a C++ base data type.  We’ll get into what this really means in a couple of weeks, but for now just realize that variables of these special types can do some special things.

All variables, regardless of its data type are declared in the same way you already know.  So, to declare a char variable and a string variable, you simply do something similar to this:
          char  ch1, ch2;
          string  str1, str2;

You can assign values using constants:
          ch1  =  'A';
          str1  =  "Hello World!";

You can assign values using other variables of the type:
          ch2  =  ch1;
          str2  =  str1;

You can assign values from the user:
          cin  >>  ch1;
          cin  >>  str1;

(More on this in the next activity.)

You can also:

        output using cout as you would expect

        pass as parameters to functions

        return from functions.

Since a string is a collection of characters, it should be possible to find out how many characters are in the string and get to the different characters individually.  And indeed we can.  If we have declared a string variable str1 then we can find out how big the string is with the following function:
          str1.length( )

Notice the name of the variable and the dot are part of the function call.  This function returns an int telling us how many characters are in the string str1.  There are no input parameters.  To find out how many characters are in string str2 you say:
          str2.length( )

The first character in the string str1 is  str1[0]  and the second character is  str1[1] .  Notice how the numbering is different?  It’s “off by one.”  Don’t forget this!  So, if the string str1 has 15 characters in it, the last one is  str1[14] .  You can use these in expressions.  For example:

                        str1[0] = str1[1];

Activity Followup

Write a C++ program, call it str.C, that reads a string from cin (after a suitable prompt of course).  Then outputs the string in two ways.  The first is using cout of the whole string.  The second uses a loop to cout each character of the string.  You must be careful to loop the correct number of times and output the correct string character. 

A sample execution might look like the following:

                  Enter a string of several characters (no spaces please):

       You entered: