【问题标题】:how do i cipher user's input in caesar cs50?我如何在 caesar cs50 中加密用户的输入?
【发布时间】:2020-06-25 08:35:07
【问题描述】:

我卡在 Pset2 中凯撒的最后一部分。我应该做的是根据用户一开始给出的密钥对用户的输入(明文)进行加密。这是我必须使用的公式:

密文第i个字符=(明文第i个字符+密钥)%26

我已经坚持了将近 2 周,但我仍然不知道如何实施该公式(尽管它是如何工作的)。这是我到目前为止所做的,但显然它有我不知道如何修复的错误。

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

int main(int argc, string argv[])                           //command line argument
{

  if (argc != 2)                                            //correct argument count
  {
    printf ("usage: ./caesar key\n");
    return 1;
  }


  for (int i = 0 ; argv[1][i] ; i++)
  {

    if (isdigit(argv[1][i]))                             //if digit = correct
    {
      printf("success\n");
    }

    else if(isalpha(argv[1][i]))                           // if letter= wrong
    {
      printf ("usage: ./caesar key\n");
    return 1;
    }

  }

  string plaintext = get_string("plaintext;");

  for( int m = 0 ; m<strlen(plaintext) ; m++)
  {
    string ciphertext[m];
    
    if(isupper(plaintext[m]))
    {
     ciphertext[m] = (plaintext[m] + argv[1]) % 26;
    }
    else if(islower(plaintext[m]))
    {
      ciphertext[m] = (plaintext[m] + argv[1]) % 26;
    }
    
    printf("%s\n", ciphertext[m]);
  }


}

【问题讨论】:

  • 公式不应该是ciphertext's i'th character = (plaintext's i'th character + i'th char of key) % 26
  • 我希望 ciphertext's i'th character = (plaintext's i'th character + key) % 26 而不是 ciphertext's i'th character = (plaintext's i'th character - 'a' + key) % 26 +'a'

标签: c cs50 caesar-cipher


【解决方案1】:

argv[1] 是一个字符串 (char*)。我希望编译器抱怨将 int 添加到 char* 中。来自the spec的提示:

回想一下,atoi 函数将看起来像数字的字符串转换为该数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2021-09-15
    • 2019-11-16
    • 2022-09-27
    相关资源
    最近更新 更多