简体   繁体   English

视觉打印垃圾信件-凯撒密码练习

[英]Visual prints garbage letters - Caesar cipher excercise

#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"


int main()
{
    char name[100];
    int key;
    printf("enter plaintext:\n");
    fgets(name, 100, stdin);
    int length = sizeof(name);
    printf("please enter key:");
    scanf("%d", &key);
    printf("plain text: %s\n", name);
    printf("ciphertext:");
    for (int i = 0; i < length; i++) {
         if (name[i] >= 65 && name[i] <= 90) {
             int c = (int)(name[i] - 'A');
             char d = 'A' + (char)((c + key) % 26);
             printf("%c", d);
        }
         else if (name[i] >= 97 && name[i] <= 122) {
                int c = (int)(name[i] - 'a');
                char d = 'a' + (char)((c + key) % 26);
                printf("%c", d);
        }
        else
           printf("%c", name[i]);
  }
    return 0;
}

Hello, So this is an exercise I have been trying to solve in the course "cs50" by Harvard. 您好,所以这是我在哈佛的“ cs50”课程中尝试解决的练习。 It's a ceaser cipher , it takes a string, a key, and prints the encryption: c=(pi+k) % 26 这是一个终止密码,它需要一个字符串,一个密钥并打印加密:c =(pi + k)%26

c - the final decrypted letter pi = the position the the letter ( a=0. b = 1..) k = the key c-最终解密的字母pi =字母的位置(a = 0。b = 1 ..)k =密钥

My program gives the right output, but the last row prints garbage chars: 我的程序给出正确的输出,但是最后一行显示垃圾字符: 在此处输入图片说明

I though it was because memory allocation? 我虽然是因为内存分配? But i haven't touched it yet, and I don't want to use the cs50.h package because I want to learn c the way it is, and not use "strings" variables like they do. 但是我还没有接触过它,我也不想使用cs50.h包,因为我想按原样学习c,并且不像它们那样使用“字符串”变量。

Any help would be appreciated. 任何帮助,将不胜感激。

Your issue is with the line 你的问题是线

int length = sizeof(name);

the sizeof operator returns the size of a variable in bytes. sizeof运算符返回变量的大小(以字节为单位)。 In this case, since name is a char[100] the size of this object is 100 bytes. 在这种情况下,由于namechar[100] ,因此此对象的大小为100个字节。 In the example you gave the plaintext (and ciphertext) were both much smaller so your loop ran over and started printing garbage memory (ie space that you allocated but didn't use to store the message). 在该示例中,您给的纯文本(和密文)都小得多,因此循环运行并开始打印垃圾内存(即,您分配但未用于存储消息的空间)。

What you need to use instead is 您需要使用的是

int length = strlen(name);

which returns the length of the string. 返回字符串的长度。 Be sure to include the string.h header. 确保包括string.h标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM