Still in desperate need of Caesar cipher help - repetition in output

You have three major problems, one you seem to have already figured out. For the first (i.e. overwriting your original message), create another char array into which you store the results of your shift. That should just involve replacing "message[i] = ch" with "whatever_you_call_your_result_array[i] = ch". Since you don't actually do any thing more than just output the results when you are just, you should move your cout statement up to just after the end of the second, inner loop. It'll allow you to only need one result array. Alternatively, you could just output the shift results as you go, but you'll need to be more careful with where you put your cout statements if you do that.

Second problem is you are not accounting for wrap around (i.e. when Z/z is encoded with a non-zero key (for example 2), the result is B/b). You're going to get non-printable characters if you just add to the ASCII value. The easiest way to do this would be to take the int value of your current character, subtract the int value of either 'a' for lower case chars and 'A' for upper case chars, perform the key shift with an alphabet size modulus (i.e. "(int_value_of_char + key_shift_value) % 26") and then finally add the appropriate int value of 'a' or 'A' back to the shifted value.

Last problem is that you are allowing for too many characters to be entered via your cin.getline call. Your original char array is only 100 characters, and by allowing getline to also store 100 chars, it is possible there will be no room left for the terminator. That could lead to an buffer overflow in your program. Bump the array size by 1 or reduce the max number of chars value passed to getline.

/r/cpp_questions Thread