This is the problem:

Write a class EncryptableString that is derived from the STL string class. The Encryptable string class adds a member function void encrypt( ) that encrypts the string contained in the object by replacing each letter with its successor in the ASCII ordering. For example, the string baa would be encrypted to cbb. Assume that all characters that are part of an EncryptableString object are letters a, .., z and A, .., Z, and that the successor of z is a and the successor of Z is A. Test your class with a program that asks the user to enter strings that are then encrypted and printed.

I wrote my code, but I can only get the output to replace the first letter with the letter A, no matter what word I input. I how would I modify the program so the first letter of the word is replaced with the seuccessive letter in the alphabet?

Here is my code so far:

#include <iostream>
#include <string>
using namespace std;
class EncryptableString: public string
{
private:
public:
EncryptableString( );
EncryptableString( string source );
void encrypt( );
string theString; //should be private, and need to include input output methods
};
EncryptableString::EncryptableString( )
{
theString = "";
}
EncryptableString::EncryptableString(string source )
{
theString = source;
}
void EncryptableString::encrypt( )
{
theString[0] = 'A';
}
int main()
{

    string word;

    cout << "Please enter a word: \n";
    cin >> word;

EncryptableString s1;
EncryptableString s2(  word  );
cout << s1.theString << endl << s2.theString << endl << endl;
s2.encrypt( );
cout << s2.theString << endl;

cin.ignore();
cin.get();

return 0;
}
Member Avatar for iamthwee

Forget the classes and object and member functions for a second.

Just concentrate on getting a simple function to work.

Come back when you have something :)

Consdider the following function that will take any string such as you described and offsets each character by a value of 1 , loops back to 'a' and keeps any capitalization:

string EncryptString()
{
    string retval;
    for(int i = 0; i < theString.length(); i++)
    {
        //temporary variable to hold each character in theString
        char temp = theString[i];
        //set offset to the beginning of the appropriate set of characters
        int offset = (temp > 90 ? 97 : 65);
        //this uses modulo(%) 26 to loop the values back to the beginning
        retval += (char)(offset + (((temp + 1) - offset) % 26));
    }
    return retval;
}

This is designed to work inside your class. To make it stand alone add 'string theString' as the parameter for the function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.