gpt4 book ai didi

c - 为什么加密代码会给出问号,而文本包含 s 后的字母并且 key 是 13?

转载 作者:行者123 更新时间:2023-12-04 07:51:37 25 4
gpt4 key购买 nike

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

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);
}

最佳答案

问题出在ch = ch + key;这一行当您有 ch 的值时和 key其总和大于可以存储在 char 中的总和多变的。例如,对于字符,'s' (ASCII 值 115)和 key13 ,总和为 128 - 溢出 8 位有符号 char (最大值 127)并导致负数。
对于大写字符,该问题发生的可能性要小得多(除非您的 key 的值非常大),因为它们的 ASCII 值要低得多('A' 到 'Z' 是 65 ... 90,而 'a' 到'z' 是 97 … 122)。
要解决此问题,请设置“临时”ch变量 an 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;
}

关于c - 为什么加密代码会给出问号,而文本包含 s 后的字母并且 key 是 13?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66942679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com