我的Cs50问题集2代码有一个随机字母为空的问题。我该如何解决?

时间:2020-06-25 19:10:35

标签: c cs50

对不起,如果我没有使用正确的术语,但是我是编码的新手,我刚开始使用cs50,我真的很喜欢它!但目前我被困在问题集2(凯撒)。我的代码有效(有点大),我的意思是90%的加密效果很好,但是在键10上方有一些空白字母,我不想这样做。非常感谢您的帮助,并为我的新手错误辩解!

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

bool check_valid_key(string s);

int main(int argc, string argv[])
{
    if(argc != 2 || !check_valid_key(argv[1]))
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    int key = atoi(argv[1]);
    {
        string text = get_string("plaintext:");
        for(int i = 0; i < strlen(text); i++)
        {
            if(text[i]>='a' && text[i]<='z')       
            {          
                text[i] += key;
                while(text[i]>'z')
                {
                    text[i]-= 26;
                }
            }
            if(text[i]>='A' && text[i]<='Z')
            {         
                text[i] += key;
                while(text[i]>'Z')
                {
                    text[i]-= 26;
                }
            }
        }      
        printf("ciphertext:%s\n", text);
        return 0;
    }       
}

bool check_valid_key(string s)
{
    for(int i = 0; i < strlen(s); i++)
    {
        if(!isdigit(s[i]))
        {
             return false;
        }        
    }
    return true;
}

2 个答案:

答案 0 :(得分:0)

问题很可能是在您的计算机上, 2020/03/20 Joe Smith Include details 2020/03/21 Bill Gates Preserve colouring and details 是一个带符号的8位值。最大值为char127的值为'z'(ASCII)。将122添加到其中会得到6 + n,但是由于它不能保存该值,因此会溢出。当有符号整数溢出时,将导致不确定的行为。

您需要检查溢出。一种方法是将128 + n转换为可以容纳更大值的类型。例如:

char

您必须对大写字母执行类似的操作。

答案 1 :(得分:0)

我不知道您是否被允许,但是您可以尝试逐字符获取输入的字符并将其加密。您将获得“空白键”或随机符号,因为char变量的范围介于-128和127之间。假设您的输入为'x',而您的 key 为< strong> 13 ,您的加密字符的值为 133 ,因为'x' ASCII 值为 120 ,将得到undefined behavior。您可以将输入变量设置为unsigned charint,它们可以容纳大于127的值(取决于编译器)。

代码:

 int c=0,key=0,old_c=0;
  
 while ((c=getchar())!=EOF&&c!='\n')
  {
    if ((c>='A'&&c<='Z')||(c>='a'&&c<='z'))
    {
      old_c=c;
      c+=key;
      while ((old_c<='Z'&&c>'Z')||(old_c<='z'&&c>'z'))
      {
        c-=26;
      }
    }
    if (c>=-128&&c<=127)
    {
      putchar(c);
    }
  }