凯撒密码仅适用于大写字母(CS50)

时间:2017-01-21 19:06:10

标签: c encryption cs50

我的程序仅适用于大写字母,我无法解决问题。一切似乎都很好,但实际上并非如此。顺便说一句,这是CS50课程(第2周)的任务。 这是我的代码:

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

int main(int argc, string argv[])
{ /* Main should take only one parameter (except program execution, of course) */
  if (argc != 2)
    return 1;

  string text = GetString(); // text to encrypt

  int i, l = strlen(text);
  int k = atoi(argv[1]); // shift value (key)
  /* Shift value should be less or equal to 26 */
  if (k > 26)
    k = k % 26;

  for (i = 0; i < l; i++)
  { /* Making sure the character to encrypt is a letter (from English alphabet) */
    if ((islower(text[i])) || (isupper(text[i])))
    {
      if ((islower(text[i])) && ((text[i] + k) > 'z'))
        text[i] = ('a' + text[i] + k - 'z' - 1);
      if ((isupper(text[i])) && ((text[i] + k) > 'Z'))
        text[i] = ('A' + text[i] + k - 'Z' - 1);
      else
        text[i] = text[i] + k;
    }
    printf("%c", text[i]);
  }
  printf("\n");

  return 0;
}

结果

caesar.exe 13
HELLO WORLD hello world
URYYB JBEYQ uryyk sknyq

1 个答案:

答案 0 :(得分:2)

整个街区;

if ((islower(text[i])) || (isupper(text[i])))
{
  if ((islower(text[i])) && ((text[i] + k) > 'z'))
    text[i] = ('a' + text[i] + k - 'z' - 1);
  if ((isupper(text[i])) && ((text[i] + k) > 'Z'))
    text[i] = ('A' + text[i] + k - 'Z' - 1);
  else
    text[i] = text[i] + k;
}

可以简化为:

if (islower(text[i]) || isupper(text[i]))
{
    int base = islower(text[i]) ? 'a' : 'A';
    int ord = text[i] - base;  // normalize text[i] to be between [0-25]
    ord = (ord + k) % 26;      // rotate
    text[i] = base + ord;      // convert back to alphabet value
}