So, first off lemme explain what a substitution code is in case you don't know. In cryptography, it's a system by which one letter is replaced with another predetermined letter. For example, if "I" turns to "E", and "F" turns to "V", the word "If" would be written as "Ev".

I'm wondering if it's possible to write a program in C++ which does this in a string for me. I'm a heavy beginner, as in only a few weeks of classes, but I think I'm getting closer and closer, but I also think I'm missing some key component knowledge.

If someone could tell me that it can actually be done, -please- do, and if you could list the concepts I'd need knowledge of, that would be even more perfect.

Tanxies for the help.

Recommended Answers

All 2 Replies

Yes, it's easy. Probably the easiest way to do it (it's not the fastest, but will probably be more than fast enough for most practical purposes) is to use a map:

std::map<char, char> key;

key['I'] = 'E';
key['F'] = 'V';
// and so on

and then you can encrypt a string as follows:

for (std::string::iterator it = str.begin(); it != str.end(); ++it)
    if (key.find(*it) != key.end())
        *it = key[*it];

The point of the if statement is to check whether the character we're inspecting is present in the map; if it isn't, we leave the character unchanged.

Thanks much!! My genius teacher is using one of the pre-standard forms of C++ to teach us, so I think I'll get on teaching myself the newer version so I can actually use that :3

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.