0
   #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' 以保持消息中的所有大写字母相同?

4

1 回答 1

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.
于 2013-01-31T22:45:29.110 回答