-2

I am trying to implement the Caesar cipher but I'm not getting the expected output. What's wrong with the code?

Key: 3
Input: Hello
Output I'm getting: KNUUX    
Expected Output: KHOOR

Code:

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

int main(int argc, string argv[])
{
    if(argc!=2)
    {
        return 1;
    }
    int k, i;
    k = atoi(argv[1]);
    printf("Enter the String to Encrypt: ");
    string s=GetString();
    for(i=0; i<strlen(s); i++)
    {
        if('A'>=s[i]<='Z')
        {
            s[i]=((s[i] - 'A' + k)%26) +'A';
        }
        else if('a'>=s[i]<='z')
        {
            s[i]=((s[i] - 'a' + k)%26) +'a';
        }
    }
    printf("The Encrypted Text is %s\n",s);        
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Use `isupper()` and `islower()` – chux - Reinstate Monica Feb 13 '14 at 03:28
  • Some advice since you're a beginner, (1) code that compiles is always helpful, (2) typedef'ing or `#define`-ing `char *` as `string` is ***not*** helpful; *ever*. – WhozCraig Feb 13 '14 at 03:32
  • @WhozCraig The typedef is part of Harvard-online's CS50 header file. It's just to skirt the issue for the first two or three weeks of the course. For this limited purpose, it is actually quite helpful. – luser droog Feb 13 '14 at 07:56

2 Answers2

3
if('A'>=s[i]<='Z')

Is certainly not doing what you seem to be expecting.

You probably want:

if ( (s[i] >= 'A') && (s[i] <= 'Z') )
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
1
for(i=0; s[i]; ++i)
    if(isalpha(s[i]))
        s[i]=(toupper(s[i]) - 'A' + k)%26 +'A';
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70