-4

The Caesar cypher encrypts text with user derfined key and text.

In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>


int main ( int argc , string argv[] )
{    
  int key,save;
  string s ;

  key = atoi(argv[1]);    
  s = GetString();

  if (  argc != 2 )
  {
    printf("prgram is yelling at you !!");
    return 1 ;
  }

  for ( int i = 0  ; s[i]!='\0' ; ++i)  // manipulation without storing character
  {
    if ( isalpha( s[i]) )           // checks whether input is in character set or not
    {
      if ( islower ( s[i] ) )       // FOR LOWER CASES
      {
        save = key % 24 ;
        s[i] = s[i] + save ;

        if ( s[i] > 'z' )
          s[i] = 'a' + ( s[i] - 'z' -1 );
      }

      if ( isupper ( s[i] ) )        // FOR UPPER CASES
      {
        save = key  % 24 ;
        s[i] =  s[i] + save ;

        if ( s[i] > 'Z' )
          s[i] = 'A' + ( s[i] - 'Z' -1 );
      }
    }

    printf ( "%c" , s[i] );
  }

  return 0 ;
}

Facts:

:) caesar.c exists 
:) caesar.c compiles
:( encrypts "a" as "b" using 1 a s key
   \ expected output, but not "b" 
:( encrypts "barfoo" as "yxocll" using 23 as key
   \ expected output, but not "yxc"
:( encrypts "BARFOO" as "EDUIRR" using 3 as key
   \ expected output, but not "EDUIRR"
   :( encrypts "BaRFoo" as "FeVJss" using 4 as key
      \ expected output, but not "FeVJss"
   :( encrypts "barfoo" as "onesbb" using 65 as key
        \ expected output, but not "srw"
   :( encrypts "world, say hello!" as "iadxp, emk tqxxa!" using   12 as key
       \ expected output, but not "adxp, em tqxxa!"

   :( handles lack of argv[1]
        \ expected output, not standard error of \      "/opt/sandbox50/bin/run.sh: line 31: 189..."
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    To start with: the formatting of your program is wrong, your program is unreadable. – Jabberwocky Jul 04 '16 at 09:53
  • I formatted the code for you to some readable format. – Jabberwocky Jul 04 '16 at 10:05
  • 1
    This looks like copy paste of question on some test server.. anyway - nice introduction but no real question, maybe you are still thinking about the question :D – nayana Jul 04 '16 at 10:06
  • why do you use string as argv? use standard char **argv or so.. also nitice that in the first line the server flagged the a->b wrong but you did printfd b.. maybe you are missing \n .. – nayana Jul 04 '16 at 10:09
  • If my answer solved your problem, click the big checkbox to accept it as the answer. This will indicate to the community that you found a solution and will give some reputation to you and the answerer. – 2501 Jul 05 '16 at 20:43
  • Note that the original (circa 1AD) Latin alphabet had 24 characters (no J, no U), but the modern Latin alphabet has 26, so using '% 24' is going to give problems. – Jonathan Leffler Aug 28 '16 at 14:45

2 Answers2

0

The problem is that you're using a char type to store the intermediate calculation which are too big for that type, instead of a larger type. This calculation:

s[i] = s[i] + save ;

the addition will be done in type int due to integer promotions, but then it will be assigned back to type char, the result will be implementation defined. It will probably wrap-around and give the invalid value.

To solve this use int to store results that

int temp = s[i] + save;
if ( temp > 'z' )
    temp = 'a' + ( temp - 'z' -1 );   
s[i] = temp;
2501
  • 25,460
  • 4
  • 47
  • 87
0

I wrote a small Caesar cipher routine in Swift using Xcode playground take a look at it, hope it helps:

            import UIKit

            let letters:[String] = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]

            var message: String = "HERE GOES THE TEXT THAT YOU WANT TO ENCRYPT"

            func encryptMessage(message: String, shift: Int) -> String {
                var count = 0
                var letterIndex = 0
                var encryptedMessage = ""
                for i in message.stringByReplacingOccurrencesOfString(" ", withString: "").characters {
                    letterIndex = letters.indexOf(String(i))! + shift
                    if letterIndex >= 26 {
                        letterIndex = letterIndex - 26
                    }
                    count = count + 1
                    encryptedMessage += letters[letterIndex]
                }
                return encryptedMessage
            }

            func decryptMessage(message: String, shift: Int) -> String {
                var count = 0
                var letterIndex = 0
                var decryptedMessage = ""
                for i in message.stringByReplacingOccurrencesOfString(" ", withString: "").characters {
                    letterIndex = letters.indexOf(String(i))! - shift
                    if letterIndex < 0 {
                        letterIndex = 26 + letterIndex
                    }
                    count = count + 1
                    decryptedMessage += letters[letterIndex]
                }
                return decryptedMessage
            }
            // Encrypt Message By Shifting 5 positions to the right in the alphabet letters array (A becomes F, B becomes G...)
            print(encryptMessage(message,shift: 5))
            // Decrypt Message By Shifting 5 positions to the left in the alphabet letters array (F becomes A, G becomes B...)
            print(decryptMessage(encryptMessage(message,shift: 5),shift: 5))
LordXmen2K
  • 29
  • 4