CS50 PSET 2 凯撒错误结果

标签 c cs50 caesar-cipher

我以为我已经完成了 Caesar,但是当运行 CHeck50 时,我的代码因以下原因失败:使用 23 作为 key 将“barfoo”加密为“yxocll” 输出无效的 ASCII 文本 日志 运行./凯撒 23... 正在发送输入 barfoo... 检查输出“密文:yxocll”...

有人能看出我的代码有什么问题吗?它似乎适用于大写字母,但对于小写字母和某些“键”,我得到了错误的结果,并且无法找出原因。任何帮助将不胜感激。

示例:如果我尝试使用 key 17 加密“foo”,它应该返回“wff”,但我的代码仅返回“w”。在我编写的代码中,它说要转到位置 128,这不是一个字母,但我的代码则说如果超过 122,则减去 26。这等于并返回“102”,- 这是“f” 。是否与删除被分配给127有关

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

int main(int argc, string argv[])
{
  if (argc == 2) {
    int a = atoi (argv[1]);
    int b = a%26;
    printf("plaintext: ");
    //get string
    string s = get_string();
    printf ("ciphertext: ");
        //iterate through string
        for (int i=0, n =strlen(s); i<n; i++) {
            //check if character is a letter
            if ( isalpha (s[i])) {
                //check if letter is uppercase
                if (isupper (s[i])) {
                    //calculate position of character in ASCI by adding 'Key'. If character is over 90, decrease character location by 26
                    char c = (s[i] + b);
                    if (c > 90) {
                            char d = c - 26;
                            printf ("%c", d);
                    } else
                    printf("%c", c);
                } else
               //For lowercase letters. If character location is over position 122, decrease location by 26
                {
                    char e = (s[i] + b);
                    if (e>122) {
                            char f = e - 26;
                            printf("%c", f);
                    } else
                        printf("%c", e);
                }
            } else    //print non letters with no change made
            {
                printf ("%c", s[i]);
            }
        }
    }
printf ("\n");
return 0;

}

最佳答案

使用小写字母,您可能会遇到溢出:

char e = (s[i] + b);

在您的系统上,char 是有符号的,这意味着它可以采用 -128 到 127 之间的值。采用小写 z,即 ASCII 122。将其移动 6 位或更多,然后你溢出了你的char。有符号整数溢出是未定义的行为。您可以通过将中间值设置为 ints 来解决此问题:

int e = (s[i] + b);

关于CS50 PSET 2 凯撒错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46325018/

相关文章:

TypeError : unsupported operand type(s) for +: 'int' and 'str' 的 Python 问题

c - 整数从字符串[]接收到错误的值

javascript - 如何处理凯撒密码 (Javascript) 中的负移位

c - 解析二进制数据时使用属性打包的结构

c++ - C/C++ 跨平台库允许利用 GPU 进行浮点计算

c - 为 socket recv TCP 设置超时

c++ - 绝对值未在 ascii 中正确添加

c - GCC过度优化?自纪元开始以来的不同秒数取决于我在哪里编译

c - do while 循环中未声明的标识符,C

c2059 do while loop C 错误,怎么了?