【问题标题】:Why does encryption code gives question mark while text contains the letters after s and key is 13?为什么加密代码带有问号,而文本包含 s 后面的字母且密钥为 13?
【发布时间】:2021-06-30 16:54:31
【问题描述】:

所以,我正在编写一个加密代码。我的代码接受单词或任何消息,并要求用户输入密钥。最终输出是加密的消息。例如:

Please enter the text you want to encrypt: hello
Enter the key: 4
The encrypted text is: lipps

但是有一个问题。当我输入包含s 的文本时,它会给出一个加密问号:

Please enter the text you want to encrypt: ssss
Enter the key: 13
The encrypted text is: ����

当我写除 13 以外的其他键并且字母为大写时,不会出现此问题。当文本包含 s (t, v, u, w, x, y, z) 之后的任何字母并且键为 13 时,就会出现此问题。

上述代码为:

#include <stdio.h>
#include <string.h>
    
int main(void) {
    int i;
    int key;
    char text[101], ch;
    printf("Please enter the text you want to encrypt: ");
    fgets(text, sizeof(text), stdin);
    printf("Enter the key: ");
    scanf("%i", &key);
    for(i = 0; text[i] != '\0'; ++i){
        ch = text[i];
            
        if(ch >= 'a' && ch <= 'z'){
            ch = ch + key;
                
            if(ch > 'z'){
                ch = ch - 'z' + 'a' - 1;
            }
                
            text[i] = ch;
        }
        else if(ch >= 'A' && ch <= 'Z'){
            ch = ch + key;
                
            if(ch > 'Z'){
                ch = ch - 'Z' + 'A' - 1;
            }
                
            text[i] = ch;
        }
    }
    printf("The encrypted text is: %s", text);
}

【问题讨论】:

  • 问题似乎是当得到的字符超过当前的字母序列('a'...'z',或'A'...'Z')然后代码不是回到那个字母序列的开头
  • text[i] = ch + 'A'
  • @kelalaka 你指的是哪一部分?
  • for(i = 0; text[i] != '\0'; ++i) --> for(i = 0; (text[i] != '\0') &amp;&amp; (text[i] != '\n'); ++i)

标签: c encryption uppercase lowercase letter


【解决方案1】:

chkey 的值的总和大于可以存储在char 变量中的值时,问题出在ch = ch + key; 行。例如,对于字符 's'(ASCII 值 115)和 key13,总和是 128 - 它溢出了一个 8 位 有符号 char(最大值 127) 并产生负数。

大写字符不太可能出现问题(除非key 的值非常大),因为它们的 ASCII 值要低得多('A' 到 'Z' 是 65 ... 90,而 ' a' 到 'z' 是 97 … 122)。

要解决此问题,请将“临时”ch 变量设置为 int,并在 所有 计算完成后将其转换回 char

#include <stdio.h>
#include <string.h>

int main(void)
{
    int i, ch; // Use an int for our temporary "ch" variable
    int key;
    char text[101];
    printf("Please enter the text you want to encrypt: ");
    fgets(text, sizeof(text), stdin);
    printf("Enter the key: ");
    scanf("%i", &key);
    for (i = 0; text[i] != '\0'; ++i) {
        ch = text[i];
        if (ch >= 'a' && ch <= 'z') {
            ch = ch + key;
            if (ch > 'z') {
                ch = ch - 'z' + 'a' - 1;
            }
            text[i] = (char)ch; // Cast the int to a char to avoid compiler warnings
        }
        else if (ch >= 'A' && ch <= 'Z') {
            ch = ch + key;

            if (ch > 'Z') {
                ch = ch - 'Z' + 'A' - 1;
            }
            text[i] = (char)ch;
        }
    }
    printf("The encrypted text is: %s", text);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2022-09-22
    • 2012-12-17
    • 2016-11-30
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 2020-09-03
    • 2012-05-30
    相关资源
    最近更新 更多