#include <stdio.h>
#include <string.h>
#include <stdlib.h>


void encrypting(char cipher[25], int shift, int num)
{
    int i;
    for (i = 0; i < num; i++)
    {
        if (cipher[i] >= 'A' && cipher[i] <= 'Z')
        {
            cipher[i] = (char)(((cipher[i] + shift - 'A' + 26) % 26) + 'A');
        }
        else if (cipher[i] >= 'a' && cipher[i] <= 'z')
        {
            cipher[i] = (char)(((cipher[i] + shift - 'a' + 26) % 26) + 'a');
        }
    }
}

void decrypting(char cipher[25], int shift, int num)
{
    inti;
    for (i = 0; i < num; i++)
    {
        if (cipher[i] >= 'A' && cipher[i] <= 'Z')
        {
            cipher[i] = (char)(((cipher[i] - shift - 'A' + 26) % 26) + 'A');
        }
        else if (cipher[i] >= 'a' && cipher[i] <= 'z')
        {
            cipher[i] = (char)(((cipher[i] - shift - 'a' + 26) % 26) + 'a');
        }
    }
}

int main()
{
    char text[10];
    static const char encrypt[] = "2";
    static const char decrypt[] = "1";
    int shift;
    char cipher[25];
    int result1;
    int result2;
    int num;
    int i;



    printf("Enter operation: encrypt or decrypt/n");
    printf("Press 1 to Encrypt or 2 to Decrypt");
    scanf("%c", &text);
    printf("Enter shift key");
    scanf("%d", &shift);
    printf("Enter text to encrypt/decrypt");
    fflush(stdin);
    scanf("%c", &cipher);

    num = strlen(cipher);

    result1 = strcmp(text, encrypt);
    result2 = strcmp(text, decrypt);

    if (result1 == 0)
    {
        decrypting(cipher, shift, num);
    }
    else { exit(0); }

    if (result2 == 0)
    {
        encrypting(cipher, shift, num);
    }
    else { exit(0); }

    printf("Result");
    printf("%d", cipher);
}


用户输入密文后,程序意外终止。我不知道现在是什么问题。谁能立即解释我的代码有什么问题?感谢所有帮助。

最佳答案

因为无论用户是要加密还是解密,您都在exit(0);之前先调用printf("Result");。更改:

else{exit(0);}

if(result2 == 0)


至:

else if(result2 == 0)


然后,如果他们既未选择加密也未选择解密,则仅调用exit(0);



另外,printf("%d",cipher);将无法打印字符串。您需要使用%s转换说明符而不是%d

关于c - C程序意外终止,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23333023/

10-09 06:05