#include <stdio.h>
int main()
{
char msg[31] = {'\0'};
char encrypted[31] = {'\0'};
int key;
printf("Please enter a message under 30 characters: ");
fgets(msg, 31, stdin);
printf("Please enter an encryption key: ");
scanf("%d", &key);
int i = 0;
if (msg[i] && (('a' >= msg[i] && msg[i]>= 'z') || ('A' >= msg[i] && msg[i] >= 'Z')))
{
i++;
} else {
while (msg[i] && (('a' <= msg[i] && msg[i]<= 'z') || ('A' <= msg[i] && msg[i] <= 'Z')))
{
encrypted[i] = (msg[i] + key);
i++;
}
}
printf("%s\n", msg);
printf("%d\n", key);
printf("%s\n", encrypted);
}
我已经有了我的代码,但我不知道如何使增量忽略特殊字符和空格。另外我如何使用%循环回'a'和'A'以保持消息中的所有大小写相同?
答案 0 :(得分:1)
你不能这样做范围测试:
'a' <= msg[i] <= 'z'
评估为'a' <= msg[i]
变为真或假(1或0),始终小于'z'
。
所以开始你需要:
( msg[i] >= 'a' && msg[i] <= 'z' || msg[i] >= 'A' && msg[i] <= 'Z' )
现在,您已将此条件置于循环中,因此只要遇到特殊字符,它就会终止。如果你想对字母有不同的行为,请在循环中检查它们:
for( i = 0; msg[i] != 0; i++ ) {
if( msg[i] >= 'a' && msg[i] <= 'z' || msg[i] >= 'A' && msg[i] <= 'Z' ) {
encrypted[i] = msg[i] + key;
} else {
encrypted[i] = msg[i];
}
}
现在问题的第二部分。您似乎想要旋转您的字母。试试这个:
// Sanity -- to avoid overflowing `char`
key %= 26;
while( key < 0 ) key += 26;
for( i = 0; msg[i] != 0; i++ ) {
if( msg[i] >= 'a' && msg[i] <= 'z' ) {
encrypted[i] = 'a' + ((msg[i]-'a' + key) % 26);
} else if( msg[i] >= 'A' && msg[i] <= 'Z' ) {
encrypted[i] = 'A' + ((msg[i]-'A' + key) % 26);
} else {
encrypted[i] = msg[i];
}
}
如果您根本不想在加密字符串中使用非字母,请创建另一个索引:
int e = 0;
encrypted[e++] = etc; // Only when you want to add something to the string.
在循环之后不要忘记:
encrypted[e] = 0; // terminate string.