Цезарь Шифр ​​не считает правильно код C - PullRequest
0 голосов
/ 14 декабря 2018

Мне нужна помощь с шифром.У меня все работает нормально, пока я не запускаю программу, нуждающуюся в возврате к 'a' после того, как она наберет 'z'.Я не уверен, как подойти к этому, поэтому любой вклад полезен.Просто чтобы прояснить ту часть, в которой я потерялся, там написано if ('c' > z).

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

// using argc and argv to get a shift number from the command line then 
// running a check to see the value of it
int main(int argc, string argv[])
{
char c;
int key = 0;

if (argc == 2)
{
    key = atoi(argv[1]);
}
else if (argc == 1)
{
    printf("ERROR\n");
    return 1;
}

string message = get_string("Enter a message to encrypt: ");
//getting the message you want to change
int len = strlen(message);

//loop to see when the array ends and run through it to
//shift each letter
for (int i = 0; message[i] != '\0'; i++)
{
    c = message[i];
//shifting the letters
    if (c >= 'a' && c <= 'z')
    {
        c = c + key;
//this is what doesn't work, when it hits z it doesn't go 
//back up and i'm not sure how to make it start at 'a' 
//again and then continue counting.
        if(c > 'z')
        {
            continue;
        }

        message[i] = c;
    }
//same as above with same error
    else if (c >= 'A' && c <= 'Z')
    {
        c = c + key;

        if (c > 'Z')
        {
            continue;
        }

        message[i] = c;
    }
}

printf("ciphertext: %s\n", message);
}

1 Ответ

0 голосов
/ 14 декабря 2018

Если вы хотите, чтобы значение типа 'z' + 1 стало a и 'z' + 2 стало b и т. Д., Вы можете изменить это:

    if(c > 'z')
    {
        continue;
    }

на что-то вроде:

    if(c > 'z')
    {
        c = c - 'z' + 'a' - 1;
    }

Кстати: ваш код не обрабатывает переполнения, поэтому он не будет работать для любого значения key.Маленькие значения ключа будут хороши, но некоторые более высокие значения ключа вызовут проблемы.Рассмотрим этот код:

#include <stdio.h>

int main(void) {
    char c = 'z';
    int key = 6;
    c = c + key;
    if ('c' > 'z')
    {
        printf("Greater than z\n");
    }
    else
    {
        printf("Less than z or equal to z\n");
    }

    int x  = c;
    printf("%d\n", x);
    return 0;
}

На некоторых платформах (например, https://ideone.com/2LOvCU) это может дать вывод

Less than z or equal to z
-128

, который, я думаю, не тот, который вы хотите. Может быть, вывместо этого следует хранить все вычисления в целочисленном типе (без знака).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...