Загрузка...

Rate the caesar cipher

Thread in C/C++ created by quozzzz Mar 9, 2023. 439 views

  1. quozzzz
    quozzzz Topic starter Mar 9, 2023 Banned 137 Feb 2, 2022
    Code
    #include <iostream>
    #include <string>

    using namespace std;

    string encrypt(string text, int shift)
    {
    string result = "";
    for (int i = 0; i < text.length(); i++) {
    if (isalpha(text[i])) {
    char c = text[i];
    if (isupper(c)) {
    result += char(int(c + shift - 65) % 26 + 65);
    }
    else {
    result += char(int(c + shift - 97) % 26 + 97);
    }
    }
    else {
    result += text[i];
    }
    }
    return result;
    }

    string decrypt(string text, int shift)
    {
    string result = "";
    for (int i = 0; i < text.length(); i++) {
    if (isalpha(text[i])) {
    char c = text[i];
    if (isupper(c)) {
    result += char(int(c - shift - 65 + 26) % 26 + 65);
    }
    else {
    result += char(int(c - shift - 97 + 26) % 26 + 97);
    }
    }
    else {
    result += text[i];
    }
    }
    return result;
    }

    int main()
    {
    int action, shift, num_letters;
    string text;

    cout << "Choose an action (1 for encryption, 2 for decryption): ";
    cin >> action;

    if (action == 1) {
    cout << "Enter the number of letters to shift: ";
    cin >> shift;
    cin.ignore();

    cout << "Enter the text to encrypt: ";
    getline(cin, text);

    string encrypted_text = encrypt(text, shift);
    cout << "Encrypted text: " << encrypted_text << endl;
    }
    else if (action == 2) {
    cout << "Enter the number of letters before the words: ";
    cin >> num_letters;
    cin.ignore();

    cout << "Enter the text to decrypt: ";
    getline(cin, text);

    string decrypted_text = decrypt(text, num_letters);
    cout << "Decrypted text: " << decrypted_text << endl;
    }
    else {
    cout << "Invalid action chosen. Please choose 1 for encryption or 2 for decryption." << endl;
    }

    return 0;
    }
     
    1. re1von
      quozzzz, вставь код нормально
    2. quozzzz Topic starter
  2. Pussy_Destroyer
    нормальный такой салат получился
     
  3. quozzzz
    quozzzz Topic starter Mar 9, 2023 Banned 137 Feb 2, 2022
    Сделал
     
  4. gpt
    статичное шифрование
     
    1. quozzzz Topic starter
      gpt, норм получилось? Не говно код?
  5. Daemon
    Daemon Mar 9, 2023 1680 Jan 8, 2021
    Начнем с того, зачем вы в условии в main скопипастили половину тела, если там 3 строки отличаются только? Сами не понимаете, что принцип DRY должен работать?
     
    1. View previous comments (5)
    2. Daemon
      quozzzz, Так же вы в функцию передаете невстроенный тип и не изменяете его, так что лучше по ссылке на константу передавать ваш text.
    3. quozzzz Topic starter
      Daemon, Понял, спасибо, завтра займусь этим
Loading...
Top