HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Implementing Caesar Cipher in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
caesarimplementingcipher

Problem

I am trying to implement a "Caeser cipher" to every lower case character in a string, by using a number to control the amount of character rotation. Here is an algorithm that I came up with. Can you please review and give me some feedback?

#include 
int main()
{
    char string4[80];
    int  rotatorN;

    printf("Enter String: ");
    gets(string4);
    printf("Enter Number: ");
    scanf("%i", &rotatorN);

    int n = 0, rotateSwap = 0;

    int i;
    for(i=0; string4[i] != '\0'; i++)
     {
          if(string4[i] >='a' && string4[i]  n )
                 {
                    rotateSwap = rotatorN - n - 1;
                    string4[i] = 'a';
                    string4[i] += rotateSwap;
                  }  
               else
                string4[i] += rotatorN;

               }
       }

      int j;
      for(j = 0; string4[j] !='\0'; j++)
        {
             printf("%c", string4[j]);
        }

        printf("\n");

        return 0;
}

Solution

You should never use gets() to read keyboard input, ever. Use fgets(), where you specify the max size of the buffer. That way, you are protecting yourself from somebody hacking your code.

You don't check input values. It is good practice to not assume a benevolent keyboard user, so, for instance, when a user enters rotatorN = -12128, you get all kinds of interesting behavior in your program.

Using scanf for input is hard to get right and therefore error-prone. Instead, use fgets for all input and then use sscanf to get the contents.

Check the calculated value for rotateSwap so that it falls within the expected range.

Context

StackExchange Code Review Q#84158, answer score: 8

Revisions (0)

No revisions yet.