EECS168 09:Lab11

From ITTC
Jump to: navigation, search
Navigation
Home
Information

Syllabus
Schedule
Lecture Notes
Exam Reviews

Classwork

Labs
Homework
Submitting Work


You are allowed 48 hours to complete this lab, instead of the usual 24.

Objectives

  • Learn to use the string class and its member functions.
  • Learn to use the vector class and its member functions.
  • Use both in creating your own program.

Using Strings

The string class provides a number of functions to simplify managing character strings.

Data input to strings

The following example shows how to save user input data as strings using cin and getline. As in previous labs, cin reads characters until it encounters whitespace. The new getline function reads characters including whitespace until it encounters a newline. Copy this code into string_input.cpp and run it. Note that getline also works with ifstream handles in addition to the cin stream object.

//Program Using the Class string
//Demonstrates getline and cin.get.
#include <iostream>
#include <string>
using namespace std;
 

void new_line( );

int main( )
{
    string first_name, last_name, record_name; 
    string motto = "Your records are our records."; 

    cout << "Enter your first and last name:\n";
    cin >> first_name >> last_name;
    new_line( );

    record_name = last_name + ", " + first_name;
    cout << "Your name in our records is: ";
    cout << record_name << endl;

    cout << "Our motto is\n"
         << motto << endl;
    cout << "Please suggest a better (one-line) motto:\n";
    getline(cin, motto);
    cout << "Our new motto will be:\n";
    cout << motto << endl;

    return 0;
}

//Uses iostream:
void new_line( )
{
    using namespace std;

    char next_char;
    do
    {
        cin.get(next_char);
    } while (next_char != '\n');
}

Strings as arrays

The following brief example shows how individual characters in a string can still be accessed directly as you are used to doing with character strings. Copy this code into string_arrays.cpp and run it.

//A string Object Can Behave Like an Array
//Demonstrates using a string object as if it were an array.
#include <iostream>
#include <string> 
using namespace std;

int main( )
{
    string first_name, last_name; 

    cout << "Enter your first and last name:\n";
    cin >> first_name >> last_name;

    cout << "Your last name is spelled:\n";
    int i;
    for (i = 0; i < last_name.length( ); i++)
    {
        cout << last_name[i] << " ";
        last_name[i] = '-';
    }
    cout << endl;
    for (i = 0; i < last_name.length( ); i++)
        cout << last_name[i] << " "; //Places a "-" under each letter.
    cout << endl;

    cout << "Good day " << first_name << endl;
    return 0;
}


Using Vectors

Vectors provide similar member functions to the string class, but are general in that they can be declared for any base variable type, not just characters. The following example shows the use of arrays of integers. Copy this code into vectors.cpp and run it.

//Using a Vector
#include <iostream>
#include <vector>
using namespace std;

int main( )
{
    vector<int> v;
    cout << "Enter a list of positive numbers.\n"
         << "Place a negative number at the end.\n";

    int next;
    cin >> next;
    while (next > 0)
    {
        v.push_back(next);
        cout << next << " added. ";
        cout << "v.size( ) = " << v.size( ) << endl;
        cin >> next;
    }

    cout << "You entered:\n";
    for (unsigned int i = 0; i < v.size( ); i++)
        cout << v[i] << " ";
    cout << endl;

    return 0;
}

Writing Your Own Programs using Strings and Vectors

Scenario: Your country is at war, and your enemies are using a secret code to communicate with each other. You have managed to intercept a message that reads as follows:
:mmZ\dxZmx]Zpgy
The message is obviously encrypted using the enemy's secret code. You have just learned that their encryption method is based upon the ASCII code. This is a system used to encode characters as numbers for use by computers. For example, the ASCII code for "A" is 65 and the code for "B" is 66. After converting each character to it's numeric ASCII code, a key is added to the number and then the new number is converted back to it's ASCII character representation. Your enemy's secret code uses the following algorithm:
/*
 * Author: Ima Student
 * Date: April 7th, 2009
 * Description: Program to encode messages using an ASCII substitution cypher
 */

#include<iostream>
#include<fstream>
#include<string>
#include<vector>

using namespace std;

void get_input(string& message, int& key);
vector<char> encrypt(string message, int key);
void display(vector<char> encrypted);
void save_file(vector<char> encrypted);

int main ()
{
	string message;
	int key;
	get_input(message, key);
	vector<char> encrypted = encrypt(message, key);
	display(encrypted);
	save_file(encrypted);
	return 0;
}

void get_input(string& message, int& key)
{
	cout << "Please enter the message to be encrypted on a single line: " << endl;
	getline(cin, message);
	cout << "Please enter a key between 1 and 100 for use in encrypting your message: ";
	cin >> key;
}

vector<char> encrypt(string message, int key)
{
	vector<char> encrypted;
	for (int i = 0; i < message.length(); i++){
		if (int(message[i]) + key > 126){
			encrypted.push_back(char(32 + ((int(message[i]) + key) - 127)));
		}else{
			encrypted.push_back(char(int(message[i]) + key));
		}
	}
	cout << endl;
	return encrypted;
}

void display(vector<char> encrypted){
	cout << "After encrypting your message reads:" << endl;
	for (int i = 0; i < encrypted.size(); i++){
		cout << encrypted[i];
	}
	cout << endl;
}

void save_file(vector<char> encrypted){
	ofstream output_file;
	output_file.open("encrypted.txt");
	for (int i = 0; i < encrypted.size(); i++){
		output_file << encrypted[i];
	}
	output_file << endl;
	output_file.close();
}

Copy the above code into encode.cpp and add comments to demonstrate that you understand how it works. You can then use it to generate additional encrypted messages for testing your next assignment. Note the use of int(char) to convert from a character to it's ASCII code and char(int) to convert from an ASCII code to its corresponding character.

Complete the program below to decrypt the intercepted message by reversing the encryption process. You only know that the key used is a number between 1 and 100. Your program should try to decode the message using all possible keys between 1 and 100. When you try the valid key, the message will make sense. For all other keys, the message will appear as gibberish. When you find the key that decrypts the message, you should verify that it is the same key that was used to encrypt the message to determine if your program is working correctly. Name your file decode.cpp.

/*
 * Author: Ima Student
 * Date: April 7th, 2009
 * Description: Program to decode intercepted encrypted messages
 */

#include<iostream>
#include<fstream>
#include<string>
#include<vector>

using namespace std;

vector<char> read_file(string file_name);
string decode(vector<char> encrypted, int key);
void display(string decrypted, int key);

int main ()
{
	vector<char> encrypted = read_file("intercepted.txt");

	// Insert appropriate function calls to decrypt the message and display the results
	
	return 0;
}

vector<char> read_file(string file_name)
{
	ifstream input_file;
	input_file.open(file_name.c_str());
	vector<char> encrypted;

	// Insert your code here to read the file into the encrypted vector;

	input_file.close();
	return encrypted;
}

string decode(vector<char> encrypted, int key)
{
	// Insert your code here to decode message
}

void display(string decrypted, int key){
	cout << "Key: " << key << " Text: " << decrypted << endl;
}

Insert code at the marked locations to make the program work.

Lab Submission

  • encode.cpp
  • decode.cpp
  • Decoded version of the intercepted message in the body of your email

The submission procedure is the same as was described in previous labs, except that:

  • Your tarball and the directory inside it should be named like Smith-1234567-Lab-11
  • The email subject should be "[EECS 168] Lab 11" (without the quotes).

Remember to include your full name, student number, and disk usage in the email.