Cereal
Cereal

Reputation: 33

C++: How do I convert each char in a string into a corresponding character?

I have a user inputted string string date (format DD-MM-YYYY) which I need to encrypt following this key 0=W, 1=x, 2=7, 3=%, 4=m, and so on...

When I input the following 12-06-1983, this is the output I'm getting 012FFAD8 - which is wrong

According to the key, the output for 12-06-1983 should be x7dW#dx&4%

Below is my code, please help me figure out the error(s). Furthermore, am I tackling this problem the correct way? Is there a simpler way to do this? Please keep in mind, this is a beginner assignment in my C++ course.

string key = date;
string encryptedKey[10];

        for (int i = 0; i < key.length(); i++) {

            if (key[i] == '0' ) {
                encryptedKey[i] = 'W';
            }
            else if (key[i] == '1') {
                encryptedKey[i] = 'x';
            }
            else if (key[i] == '2') {
                encryptedKey[i] = '7';
            }
            else if (key[i] == '3') {
                encryptedKey[i] = '%';
            }
            else if (key[i] == '4') {
                encryptedKey[i] = 'm';
            }
            else if (key[i] == '5') {
                encryptedKey[i] = 'G';
            }
            else if (key[i] == '6') {
                encryptedKey[i] = '#';
            }
            else if (key[i] == '7') {
                encryptedKey[i] = 'P';
            }
            else if (key[i] == '8') {
                encryptedKey[i] = '4';
            }
            else if (key[i] == '9') {
                encryptedKey[i] = '&';
            }
            else if (key[i] == '-') {
                encryptedKey[i] = 'd';
            }
            else {
                cout << "\nError.\n";
            }
        }

cout << encryptedKey;

Upvotes: 2

Views: 180

Answers (1)

Joshua K
Joshua K

Reputation: 2537

You have to replace string encryptedKey[10] by string encryptedKey = "0000000000"; and your code works like expected. It's not smart, but it works.

Better of using nested if statements use switch-case.

In your code there is no need for if or switch-case. just use a map to translate your input string.

string key = "12-06-1983";
string encryptedKey = "";
map<char, char> replacements = {
    { '0', 'W' },
    { '1', 'x' },
    { '2', '7' },
    { '3', '%' },
    { '4', 'm' },
    { '5', 'G' },
    { '6', '#' },
    { '7', 'P' },
    { '8', '4' },
    { '9', '&' },
    { '-', 'd' }
};
for (int i = 0; i < key.length(); i++) {
    encryptedKey += replacements.at(key[i]);
}

cout << "Key: " << encryptedKey;

The map defines which character is to replace with which other. Now just iterate over the input and lookup the map which character should placed inside the encryptedKey instead of the given.

Here is a working online example code by cpp.sh

Upvotes: 4

Related Questions