Welcome to Lesson 6!

Learning Objetives
By the end of today's class, you should know...
  • What is ASCII?
  • What is a string?
  • What is the difference between a char and a string?
  • How do you declare a string variable and assign it a value?
  • How do you output a string to the console?
  • How do you read in a string from the console and store it in a variable?
  • What is the problem you may run into when using cin with strings?
  • What is string concatenation?


  • Quiz 2 after our break!
  • Lab 4 posted for Friday!

Review of Assigning Variables

With a partner, determine what gets printed to the console in parts 1 and 2:

Part 1:

//assume below statement are part of a main function

int oranges = 12;
int apples = 4;
oranges = apples;
int numFruit = apples + oranges;
apples = apples - 2;
cout << "Apples: " << apples << endl;
cout << "Oranges: " << oranges << endl;
cout << "Total Fruit: " << numFruit << endl;

Part 2:

1. cout << 7 / 2.0;

2. cout << 7 / 2;

3. cout << 7 % 2;

4. int result = 7.0 / 2.0;

   cout << result;

5. cout << 9 + 3 * 5 / 2 - 3;

Part 3:
  • Write a complete user interaction (3 lines of code) to prompt a user to enter a weight, read in the weight from the user and store the result in a variable.

Review of Char

  • In addition to numbers, computers can manipulate text and other non-numerical types
  • Values of type char (short for character) are a single letter, number or special symbol
  • You specify a character by enclosing it in single quotes (')
    • The quote marks are not part of the data
  • For example:
    'a'   'b'   'Z'   '3'   'q'   '$'   '*'
  • When you use a char data type, you store the character using an ASCII code
  • ASCII is a coding method that assigns a number to every character
  • You can see the codes in an ASCII Table

Char Variables - Declaring and Assigning

  • As with other data types, you must declare char variables before use:
    char letter;
  • You assign values to a char variable using the equals sign:
    letter = 'A';
  • Just like numerical types, you can combine declaration and assignment into one statement:
    char letter = 'A';
  • Also like numerical types, you can declare multiple variables on one line:
    char letter, letterA = 'A', letterB = 'B';

User I/O with Type char

  • Like numbers, you can output type char using cout <<
    char letter = 'A';
    cout << letter << 'B' << endl;
  • Also, you can input type char using cin >>
    cin >> letter;
    cout << letter  << endl;

Activity 6.1: My Initials (10 pts)
  • Here is an ASCII conversion chart (also depicted below). Each letter of the alphabet and all symbols on your keyboard (and some that aren't) are represented as numerical values in ASCII.


  • Let's test the ASCII conversion codes and make sure that they really do work, by writing a program to print out your name.
  • Open a new C++ source file named initials.cpp
  • Copy and paste the example code below into your program.
  • Alter the values for your own initials.
* Jennifer Parrish
* CIS 22A
* M/W 9:30-11:20am

using namespace std;

int main(){
    char first = 74;
    char second = 90;
    char third = 80;

    cout << "My initials are: " << first << second << third << endl;

    int initial1 = 'J';
    int initial2 = 'Z';
    int initial3 = 'P';

    cout << "The ASCII values of my initials are:\n";
    cout << initial1 << endl << initial2 << endl << initial3 << endl;
    return 0;

  • The take away: You can use ASCII numbers and chars interchangeably.
  • Also try the reverse: declare 3 integer variables and assign your initials as chars to each of the variables as in the example above.
  • Will your code compile? What happens when you run it?
  • When you are finished upload your initials.cpp file to Canvas.

Introduction to Strings

  • In addition to single characters, computers can work with text strings
  • For example, in the following the characters between the double quotes are displayed as text:
    cout << "Hello World!" << endl;
  • Programmers refer to text like this as a string because it is composed of a sequence of characters that we string together
  • C++ provides the string type so we can work with text
  • To work with the string type we may need to include the string library:
    #include <string>
    using namespace std;
  • Strings are enclosed in double quotes, which are not part of the string
  • For example:
    "Hello"  "b"  "3.14159"  "$3.95"  "My name is Fred"
  • Notice that the string "3.14159" could be expressed as a double by removing the quotes
  • However, a computer stores these two values very differently and we must use them in different ways
  • For instance, we cannot multiply the "3.14159" by 2, but we can when it is expressed as a double:
    cout << "3.14159" * 2; // NO!
    cout << 3.14159 * 2; // allowed 

String Variables and Simple I/O

  • We declare and assign values to string variables like numeric types
  • For example:
    string firstName;             // declaration
    firstName = "Jennifer";       // assignment
    string lastName = "Parrish";  // declaration + assignment
    cout << firstName << " " << lastName << endl;

Simple I/O with Strings

  • Like numbers, you can output type string using cout <<
  • Also, you can input a string using cin >> stringName
  • For example:
    string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "You entered: " << name  << endl;
  • The cin statement assigns the user input to the string variable name
  • Note that only a single word can be entered using cin >> name
  • This is because cin >> name works as follows:
    1. Skips whitespace
    2. Reads non-whitespace characters into the variable
    3. Stops reading when whitespace is found

Joining Strings (Concatenation)

  • You can join two strings together using the '+' operator
  • The join operation is called concatenation
  • For example:
    string s1 = "Hello", s2 = "World!";
    string s3 = s1 + s2;
    cout << s3 << endl;
  • The string s3 now has the contents of both s1 and s2
  • You can also mix string variables and literal strings:
    string s1 = "Hello", s2 = "World!";
    string s3 = s1 + ", " + s2;
    cout << s3 << endl;
  • One or both strings surrounding the + must be a string variable
  • For instance, the following will NOT work:
    string greeting = "Hello" + " " + "World!"; // No!
  • However, this is not usually a problem because we can just make one long literal string:
    string greeting = "Hello World!";
  • In addition, we can concatenate strings and characters:
    char letter = 'A';
    string s1 = "BC";
    s1 = letter + s1 + 'D';

Activity 6.2: My Name (10 pts)

  • Find a partner for pair programming, then open a new C++ project in Eclipse called Name
  • Save the file as name.cpp
  • We will create a program to greet the user by name.
  • Add a block comment at the top of your program with your name and section information.
* Name of partner 1
* Name of partner 2
* Section info
  • Now add a statement to include the iostream library.
  • Don't forget to use the standard namespace.
  • Create your main function and leave extra space to write your program statements.
  • Your program should now look like this:

  • At the top of the main function, let's declare our first string variable - to store the first name of our user:
string first_name;
  • Declare a second string variable to store the last name of our user in the same _ style.
  • Declare a third string variable to store the user's full name:
string full_name;
  • Welcome the user with a cout statement like this one:
cout << "Hi! I want to learn your name!" << endl;
  • Now, prompt the user to enter their first name.
cout << "Please enter your first name: ";
  • Follow this prompt with a cin statement to capture the user input.
cin >> first_name;
  • Now prompt the user to enter his or her last name and store the input in the last_name variable.
  • We want to assign the full_name variable the value of the user's first and last name combined. Let's do so now using concatenation:
full_name = first_name + " " + last_name;
  • Finally, let's greet the user by his or her full name.
cout << "Nice to meet you " << full_name << "!" << endl;

  • Run your program to ensure it is giving you the output you expect.
  • When you are finished upload your name.cpp file to Canvas

Strings Continued

String Functions

  • Strings are a special type of variable called objects, which you will study in more detail in CIS 22B.
  • An object is a data type that can have functions associated with it
  • These functions are called member functions and are called using dot notation
  • The syntax for calling a member function of a string object is:
  • Where:
    • stringName: the name of the string variable
    • functionName: the name of the member function
    • arguments: the function input values, if any
  • Once you create a string variable, you can call (invoke) its member functions

Some Commonly-Used Functions

  • length(): Returns the number of characters in a string
    string str = "Hello";
    cout << "The number of characters is " << str.length()
         << ".\n";
  • substr(in): Returns a substring of length n starting at index i
    string greeting = "Hello, World!\n";
    string sub = greeting.substr(0, 4);
    cout << sub << endl;
  • The position numbers in a string start at 0. The last character is always one less than the length of the string
  • sub = greeting.substr(7, 5);

  • Remember: length() gives you the number characters in the string

    • However: Indexing starts at 0, so the last character is always at index length()-1

Example Using String Functions

  • Consider the problem of extracting the initials from a person's name
  • What would be an algorithm for solving this problem?
  • To implement this algorithm, we can use the string function substr()
  • The following program implements an algorithm for extracting the intials from a person's name
  • What other technique could you use to extract the initials?

Activity 6.3: My Name 2 (10pts) 

  • Find a partner for pair programming.
  • Open up your name.cpp file from the last class and let's add to it.
  • Don't forget to include your partner's name in the block comment at the top of the program.
  • First, let's alter the program so that it prompts the user for his or her first and last names in a single prompt instead of two.
Please enter your first and last name:
  • Now, follow the prompt with two cin statements. One to input the first name and one to input the last name.
  • Alternately, you can write the above with a single cin statement that stores the input in the two separate first_name and last_name variables.
  • Keep the rest of the program the same. We are going to add to it.
  • Let's calculate the length of the user's first and last names and output the result to the console
cout << "The length of your first name is " << first_name.length() << " letters\n";
  • Now add a similar cout statement to display the length of the user's last name AND full name (remember the full_name variable)
  • Take a look at the sample output below. Notice that there is a mistake in the line in purple.
    • What is the cause of this mistake?
    • How can you fix this mistake so that the correct number of letters is displayed?
  • Next, let's return the user's initial's to them.
  • Let's declare a new string variable called initials that you place at the top of your program with the other variable declarations.
string initials;
  • Next, we are going to use the substr() function to extract the initials from the user's first and last names.
  • A person's initials are composed of the first letters of their first and last names.
  • Therefore, we need the letters at position 0 in the first_name and last_name variables.
initials = ??????? + ???????; //How do you call the substr() function to get the initials
  • Next, print the results to the console to display for the user.
cout << "Your initials are: " << initials << endl;

  • Submit your name.cpp program to Canvas.
  • Remember that both partners need to submit for full credit.

The output of your program should look like this:

Hi! I want to learn your name.
Please enter your first and last name: Jennifer Parrish
Nice to meet you Jennifer Parrish!
The length of your first name is 8 letters
The length of your last name is 7 letters
The length of your full name is 16 letters //Please fix this line before you submit
Your initials are: JP

Output of Hard-to-Print Characters
  • We have been using the << operator to output strings
    string msg = "Hello Mom!";
    cout << msg << endl;
  • However, some characters are more difficult to output than others
  • For example, what would the compiler do with the following statement?
    cout << "Say, "Hey!"" << endl;
  • Some characters cannot be output directly in a string
  • Also, the first 32 ASCII characters are not visible on our monitors
    • Known as control characters because they control the output device
  • Even though these characters are not visible, we sometimes need to use them
    • For example, a newline character
  • We need some way to "print" invisible and hard-to-print characters

Escape Sequences

  • C++ can access control codes and hard-to-print characters using escape sequences
  • Backslash (\) directly in front of a certain character tells the compiler to escape from the normal interpretation
  • The following table has some nonprinting and hard-to-print characters:
\aAlert (sound alert noise)
\fForm feed
\nNew line
\rCarriage return
\tHorizontal tab
\vVertical tab
\'Single quote
\"Double quote
\oooASCII character in octal notation
\xhhhASCII character in hexadecimal notation
  • Some examples:
    cout << '\a' << endl; // alert
    cout << '\n' << endl;
    cout << "Left \t Right" << endl;
    cout << "one\ntwo\nthree" << endl; 

Wrap up

With a partner, answer the following questions:
  • What will the following statements output to the console:
char letter1 = 67;
char letter2 = 111;
char letter3 = 108;
char punctuation = 33;
cout << letter1 << letter2 << letter2 << letter3 << punctuation;
  • Is the following statement legal? Why or why not?
cout << "39" + 2;

Now, alter the above statement to make it legal (two possible changes you could make).
  • Using string concatenation and the string variables below, declare a fourth string variable that contains the following: Thank you for your order, Shinshin! (Note: pay careful attention to the two punctuation marks in the previous sentence)

string grateful = "Thank you for your order";

string name = "Shinshin";

string punctuation = "!";

Assignment 6 due Monday at 9:20am
Lab 4 due Friday at Midnight
~See You Wednesday!~