vendredi 28 juin 2019

Simple Cypher Program Not Resetting Correctly

I'm learning programming and c++ as my first language for fun. I'm trying to create a simple program that encrypts and decrypts input so I can practice with strings.

Everything works okay, but somehow I am ending up with old inputs popping up when i run the program again for a second time.

For example if I input "greg" , then decrypt it, then enter greg again, I get two "greg"(encrypted)- so it's not resetting correctly, it will keep adding new words on without resetting.

#include <iostream>
#include <string>

using namespace std;

int main() {
  string alphabet{"a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 "
                  "5 6 7 8 9 0"};
  string key{"m h i p g f b t x u r l w a j e q k z d y v o c n s 9 5 0 7 8 2 "
             "3 4 1 6"};
  string word{};
  string secretword{};
  string decryptedword{};
  int selection{};
  // int newpos {};
  int position{};
  int keypos{};

  do {
    cout << "-------------------------------------" << endl;
    cout << "Select an Option: " << endl;
    cout << "1: Encrypt" << endl;
    cout << "2: Decrypt" << endl;
    cout << "3: Quit" << endl;

    cin >> selection;

    if (selection == 1) {
      cout << "Enter a Word to Encrypt:";
      cin.sync();
      getline(cin, word);

      for (auto i : word) {
        if (isupper(i)) {
          cout << "Please use lower case only" << endl;
          break;
        }

        position = alphabet.find(i);
        secretword += key.at(position);
      }
      cout << "Encrypted Word: " << secretword << endl;
      secretword = "";
    }

    if (selection == 2) {
      cout << "Enter a Word to Decrypt: ";
      cin.sync();
      getline(cin, secretword);

      for (auto i : secretword) {
        if (isupper(i)) {
          cout << "Please use lower case only" << endl;
          break;
        }
        position = key.find(i);
        decryptedword += alphabet.at(position);
      }

      cout << "Decrypted Word: " << decryptedword << endl;
      decryptedword = "";
    }
  } while (selection != 3);

  return 0;
}

Aucun commentaire:

Enregistrer un commentaire