Activity 6-2: New Data Types

Activity Goals

To get familiar with using
the char and string data types

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:charch1, ch2;stringstr1, 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 isstr1[0]and the
second character isstr1[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 isstr1[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):Hello_how_are_you_doing?