所以主要的问题是,在输入的字符串中添加(-5到4)的字符是混乱的,以显示可能被加密的单词。当循环运行时,输入字符不是起点,因此其他所有内容都将被抛弃。另外,我不能让repeat = false语句注册。
#include<stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main()
{
char encrypted_string[100];
char z;
char stop[]="STOP";
int x=-5, y, len;
bool repeat = true;
while (repeat)
{
printf("Enter the encrypted word (type STOP to quit) : ");
fgets(encrypted_string, 100, stdin);
if (strcmp(encrypted_string, stop)== 0)
{
repeat = false;
}
//len=strlen(encrypted_string);
while (x < 5)
{
for (y = 0; encrypted_string[y] != ' '; y++)
{
z = encrypted_string[y];
if (z >= 97 && z <= 122)
{
z=z+x;
if (z < 97)
{
z=z+(122-97)+1;
}
encrypted_string[y] = z;
}
else if (z >= 65 && z <= 90)
{
z=z+x;
if (z < 65)
{
z=z+(90-65)+1;
}
encrypted_string[y] = z;
}
}
printf("For shift of %d, decrypted word is %sn", x++, encrypted_string);
}
}
return 0;
}
char stop[]="STOP";
fgets(encrypted_string, 100, stdin);
if (strcmp(encrypted_string, stop)== 0)
fgets()
在缓冲区中留下尾随换行符,因此如果用户在行尾按enter键,这将永远不会为真。
if (z >= 97 && z <= 122)
这些看起来有点像魔术数字,可能写成'a'
和'z'
更好。
if (z >= 97 && z <= 122) {
z=z+x;
if (z < 97)
如果增量x
是正的呢?z
可以超过122。
实际上,为什么它被命名为x
?它是移位偏移量,就这么叫它。类似地,y
是一个索引,所以可以改为i
。尤其令人困惑的是,你有x
,y
和z
,这是三个完全不同的东西。
while (x < 5) {
for (y = 0; encrypted_string[y] != ' '; y++) {
...
encrypted_string[y] = z;
您正在修改下次迭代时再次读取的同一字符串。对于输入foo
,它进行-5的移位得到ajj
,然后再进行-4的移位得到wff
,以此类推。