Caesar cipher encoding in C++: chars won't loop back to 'a' or 'A' -


i'm working on coding ceasar cipher reads plaintext .txt, encrypts plaintext , writes second .txt, reads second .txt , decrypts third .txt. working except encryption of characters near end of alphabet. when character reaches 'z' or 'z' should loop 'a' or 'a'. below snippet of code encoding function, bit that's causing issues.

if (isalpha(inputstring[i])) {         //use isalpha() ignore other characters     (int k = 0; k < key; k++) {     //key calculated in function, 6 in case         if (inputstring[i] == 'z')      //these statements don't seem work             encryptedstring[i] = 'a';         else if (inputstring[i] == 'z')             encryptedstring[i] = 'a';         else                            //this part works correctly             encryptedstring[i] ++;     }                } 

input:

the quick brown fox

jumped on the----

house or moon or some-thing.

expected output:

znk waoiq hxuct lud

pasvkj ubkx znk----

nuayk ux suut ux yusk-znotm.

actual output:

the q{ick bro}n fo~

j{mped o|er the----

ho{se or moon or some-thing.

key: 6

share|improve question
1  
welcome stack overflow! sounds may need learn how use debugger step through code. debugger, can execute program line line , see deviating expect. essential tool if going programming. further reading: how debug small programs – nathanoliver apr 7 @ 16:59
1  
there's bug somewhere in code. if showed us, might able find it. iow, please provide minimal, complete, , verifiable example. – angew apr 7 @ 17:14
    
if remember correctly caesar cipher adding key , modulo number of letters in alphabet. can ciphered[i] = (input[i] + key) % ('z' - 'a') + 'a' – zivs apr 7 @ 17:24
    
@zivs need "offset" well, +'a'. otherwise won't valid ascii. – jonas apr 7 @ 17:25
    
@jonas, yes fixed it... – zivs apr 7 @ 17:26
up vote 2 down vote accepted

you modifying encryptedstring , basing "loop-over" decision on inputstring.

i suspect want firstly initialize encryptedstring inputstring, , work on encryptedstring. looks, me, should this:

encryptedstring[i] = inputstring[i]; // initialize encryptedstring if (isalpha(inputstring[i])) {     (int k = 0; k < key; k++)     {         if (encryptedstring[i] == 'z') // read encryptedstring instead of inputstring             encryptedstring[i] = 'a';         else if (encryptedstring[i] == 'z') // read encryptedstring instead of inputstring             encryptedstring[i] = 'a';         else             encryptedstring[i] ++;     }                } 
share|improve answer
1  
changing input encrypted string fixed it. did set encryptedstring = inputstring earlier in code (right after pulled line txt file). – nick biederman apr 7 @ 17:32

your answer

 
discard

posting answer, agree privacy policy , terms of service.

not answer you're looking for? browse other questions tagged or ask own question.

Comments