This is a discussion on Encryption within the C Programming forums, part of the General Programming Boards category; dfgh...
Last edited by 4658dan; 12-10-2010 at 01:23 PM.
Your loop should beWhen you add the offset to count, you should ensure that count does not exceed the alphabet bounds. Wrap it around.Code:for (count=0; count < 26; count++)
What if a letter is not found such as punctuation and spaces? How do you want those encrypted?
You can tell if a letter was not found in the alphabet by count having reached 26... (you didn't break out of the loop). In that case you can just output the untranslated character. Assign code = i so that your translating code passes the value: fprintf(myfile, "%c", alpha[code]). But you're missing some closing braces which means I have to make assumptions.
Ok, i see what you mean but how do i do it so 'z' will wrap back round to'a' if offset is 1? Also it only writes one letter to the file? Any ideas? Thanks again.
The wrap-around issue: if count + shift is 26, it should be 0 ('Z' becomes 'A'). If the total is 27, it should become 1. See the pattern? Subract 26 to wrap it.
I mentioned your problem with closing braces. I am not sure where you meant your fopen to go. Surely not inside the loop. Only open/create the file once. Then the character writing should be in the for (i loop. But not any deeper.
You are not handling bothg upper and lower case yet.
You need to move your fopen("encrypted.txt to before the for (i loop.Code:count += shift; if (count > 25) count -= 26;
You need to determine if the character was found in the alphabet at all.
fprintf(myfile, "%c", alpha[count]); would go inside the last brace in the above snip. So it writes at the same rate as the i variable traverses through.
The way you have the loops coded you can't tell if count ended up to be 26 because of some character + offset, or because the loop simply ran to the end (punctuation, space, etc.). I would suggest using a new variable to store the translated index. That way you can still check whether count reached 26 after the loop.