【问题标题】:Caesar’s cipher encryption program in CC 中的凯撒密码加密程序
【发布时间】:2016-04-27 17:42:16
【问题描述】:

我正在将此代码用于 Caesar 的密码加密程序。 c = (alpha + k) % 26; //c = 密文 ASCII 码,“alpha”字母 ASCII 码,“k”密钥为密文;这个等式在所有 26 个字母上给了我零 (0)。

谢谢!

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

int main (int argc, string argv[]) {

    // took key from user and converted it to int
    int k = atoi (argv[1]);

    // get plaintext from user
    string p = GetString ();

    int c = 0, alpha = 0;

    for (int i = 0, n = strlen(p); i < n; i++)
    {
        // if it is alphabet else if not alphabet
        if (isalpha (p[i]) == true) {

            // if it is capital case else lower case
            if (isupper(p[i]) == true) {
                alpha = p[i] - 65;

                // add key to plaintext then take modulas
                c = (alpha + k) % 26;

                alpha = c + 65;
            } else {
                alpha = p[i] - 97;

                // add key to plaintext then take modulas
                c = (alpha + k) % 26;

                alpha = c + 97;
            }

        } else {
            alpha = p[i];
        }

        printf("%c \n",  alpha);
    }
}

【问题讨论】:

  • 您使用的是 C 还是 C++。你说 C 但你标记为 C++。
  • 你试过调试了吗?
  • 与您的问题无关,但请尽量避免magic numbers,例如65。请改用 'A' 等正确的字符文字。
  • 有趣,以前从未见过int main (int argc, string argv[])
  • 代码不完整。可能没有人,但你的班级有 cs50.h。没有它,您的代码将无法编译。

标签: c encryption cs50 caesar-cipher


【解决方案1】:

来自isalpha的文档

如果 c 是特定的,则这些例程中的每一个都返回 nonzero 字母字符的表示

因此,当您说 if (isalpha (p[i]) == true) 时,您是在比较 isalpha()(可能不是 1) 返回的 非零 值与 1 (true) 可能不成立,if 块将不会被执行。 isupper() 也是如此。所以基本上我不认为方程给你零,它只是方程所在的if块没有被执行。

你可能想这样做:

if (isalpha(p[i])
{

   if (isupper(p[i])
   {
      //your code
   }
   ...//your code
}

【讨论】:

  • 我从不使用 C 的 bool 添加,这是原因之一。 0 是假的,其他都是真的。 if (isalpha (p[i]) != false) 是不必要的笨拙,当语言习语是 if (isalpha (p[i]))
  • @Weather Vane 完全正确!
  • @kfsone 你应该回答这个问题。它解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多