【发布时间】: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') && (text[i] != '\n'); ++i)
标签: c encryption uppercase lowercase letter