Jesse Hix
Jesse Hix

Reputation: 93

Issues with a Caesar Cipher

So the main issue is that the addition of (-5 to 4) to the characters in the entered string is all messed up to show possible words that were encrypted. When the loop runs the enter characters are not the starting point thus throwing everything else off. Additionally, I cannot get the repeat = false statement to register.

#include<stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
 
int main()
{
    char encrypted_string[100];
    char z;
    char stop[]="STOP";
    int x=-5, y, len;
    bool repeat = true;

    while (repeat)
    {
        printf("Enter the encrypted word (type STOP to quit) : ");
        fgets(encrypted_string, 100, stdin);
        if (strcmp(encrypted_string, stop)== 0)
        {
            repeat = false;
        }
        //len=strlen(encrypted_string);
        while (x < 5)
        {
            for (y = 0; encrypted_string[y] != '\0'; y++)
            {
                z = encrypted_string[y];
                
                if (z >= 97 && z <= 122)
                {
                    z=z+x;
                    
                    if (z < 97)
                    {
                        z=z+(122-97)+1;
                    }
                    
                    encrypted_string[y] = z;
                }
                else if (z >= 65 && z <= 90)
                {
                    z=z+x;
                    
                    if (z < 65)
                    {
                        z=z+(90-65)+1;
                    }
                    
                    encrypted_string[y] = z;
                }
            }
            printf("For shift of %d, decrypted word is %s\n", x++, encrypted_string);
        }  
    }  
    return 0;
}

Upvotes: 1

Views: 56

Answers (1)

ilkkachu
ilkkachu

Reputation: 6517

char stop[]="STOP";
    fgets(encrypted_string, 100, stdin);
    if (strcmp(encrypted_string, stop)== 0)

fgets() leaves the trailing newline in the buffer, so this will never be true if the user hit enter at the end of the line.

            if (z >= 97 && z <= 122)

These look a bit like magic numbers, probably better to write 'a' and 'z' instead.

            if (z >= 97 && z <= 122) {
                z=z+x;
                if (z < 97)

What if the increment x is positive? z could go over 122.

Actually, why is it named x? It's the shift offset, so call it that. Similarly, y is an index, so perhaps i instead. Especially confusing is that you have x, y and z that are three totally different things.

while (x < 5) {
    for (y = 0; encrypted_string[y] != '\0'; y++) {
        ...
        encrypted_string[y] = z;

You're modifying the same string you read again on the next iteration. For the input foo, it does a shift of -5 giving ajj, then a shift of -4 from that, giving wff, etc.

Upvotes: 2

Related Questions