0

For Caeser I prompt a string from the user which I want to 'analyse' inside a for loop. Where I pick every char of the string and change the letters of the string.

for (int i = 0, n = strlen(message); i < n; i++)
{

int key = atoi(argv[1]);

int c[i] = ( %c[i] + key ) % 26;

}

What's the right way to pick the array of chars from a string and put them with [i] in a formula?

0

Your biggest problem is that you are redeclaring key and c on every pass through the loop.

First, let's talk about key and argv. Just to be clear,atoi(argv[1]) operates on the entire string at argv[1], not on individual characters. There's no need to have it inside the loop. Doing so is inefficient for two reasons - you're both redeclaring key and running atoi() a total of n times. Not a big deal, but these things add up, especially in software that executes thousands or millions of times.

Next, lets look at the following:

int c[i] = ( %c[i] + key ) % 26;

The int at the beginning of the line redeclares the array on each pass, so the data from the previous pass is lost. Next, the % operator is like any other mathematical operator. It needs two operands - one on each side. You only have one in the firse usage. Try the following instead:

int key = atoi(argv[1]); 
string c = //whatever you want to put in it - don't want to give away too much. ;-)

for (int i = 0, n = strlen(message); i < n; i++)
{
    c[i] = ( c[i] + key ) % 26;
}

That's the answer to your question. It's easy to guess what you're trying to do here, and there are issues that you'll soon discover, but that's another question entirely and I don't want to take away all the fun!

If this answers your question, please click on the check to accept. Let's keep up on forum housekeeping. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .