0
#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(int argc, string argv[])
{
if (argc != 2) 
{
    printf("Please enter 1 additional numeric Command-Line argument!\n");
    return 1;
}

string plain;
int cipher = atoi(argv[1]);
int cipherMod;

printf("plaintext: ");
plain = get_string();

for (int i = 0, n = strlen(plain); i < n; i++) 
{
  if (i == 0) {
    printf("ciphertext: ");
  }  

  if (plain[i] >= 'A' && plain[i] <= 'Z') 
  {
    if (cipher > 26)
    {
      cipherMod = cipher % 26;
      plain[i] = plain[i] + cipherMod; 
      printf("%c", plain[i]);
    }
    else
    {
    plain[i] = plain[i] + cipher; 
    printf("%c", plain[i]);
    }
  }

  if (plain[i] >= 'a' && plain[i] <= 'z')
  {
    if (cipher > 26)
    {
      cipherMod = cipher % 26;
      plain[i] = plain[i] + cipherMod; 
      printf("%c", plain[i]);
    }
    else
    {
    plain[i] = plain[i] + cipher; 
    printf("%c", plain[i]);
    }
  }


  }

      printf("\n");
}

I have the issue, that the code works fine so far, but at the check a input of boofar with 23 or higher encryption and also the world, say hello is not being ciphered sucessfully! I see my Problem going down to the fact that for example the 'r' goes through the roof with a key of 23 because it leaves the boundary of the ASCII Table, but i donĀ“t know how to exactly limit this yet...

Sry, for my english, it is not my native language ;)

2

It's not enough to apply the %26 to the cipher. You need to shift your character into range 0-25

plain[i] - 'A'

then add cipher

plain[i] - 'A' + cipher

then apply %26 to wrap numbers back to 0-25

(plain[i] - 'A' + cipher) % 26

and shift back to letters

(plain[i] - 'A' + cipher) % 26 + 'A'

Similar for lowercase, just using 'a' instead of 'A'.

Also, structure should be like

if uppercase
    use 'A' in formula
else if lowercase
    use 'a' in formula
else
    print character as-is
  • Damn, after using your approach i just realized that half of my Code became obsolete. Thank you very much :) – Daniel Böhme Mar 29 '17 at 10:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .