I am trying to implement Caesar Cipher using C++. The directions are to use this file which is already encrypted:
5
Asi ymj rtrjwfymjx tzylwfgj.
Aqq rnrxd bjwj ymj gtwtlwtajx
Dni ldwj fsi ldrgqj ns ymj bfgj.
Tbfx gwnqqnl fsi ymj xnymjd ytajx
The number 5 represents the shift that is applied to the text. I have to decode the Caesar ciphered text and reverse the lines as in put line 4 in line 1's position and line 3 in line 2's. The first letter of each line does not need to be decoded (the uppercase letters).
The text should look like this after running the program:
Twas brillig and the sithey toves
Did gyre and gymble in the wabe.
All mimsy were the borogroves
And the momerathes outgrabe.
As of right now, I have this code:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
char decipher (char c, int shift);
int main(){
    //declare variables
    char c;
    string deciphered = "";
    int shift;
    vector <string> lines;
    //ask for filename and if not found, keep trying
    ifstream inFile;
    string filename;
    cout << "What is the name of the file? ";
    cin >> filename;
    inFile.open(filename);
    while (!inFile){
        cout << "File not found. Try again: ";
        cin >> filename;
        inFile.open(filename);
    }
    //find shift from file
    inFile >> shift;
    //get lines from file
    inFile >> noskipws;
    while (inFile >> c){
        char decipheredChar = decipher (c, shift);
        deciphered += decipheredChar;
    }
    cout << deciphered;
}
char decipher (char c, int shift){
    string letters = "abcdefghijklmnopqrstuvwxyz";
    if (c == 'T'){
        return c;
    }
    else if (c == 'D'){
        return c;
    }
    else if (c == 'A'){
        return c;
    }
    else if (c == ' '){
        return c;
    }
    else {
        int currentPosition = letters.find(c);
        int shiftedPosition = currentPosition - shift;
        if (shiftedPosition < 0){
            shiftedPosition = 26 + shiftedPosition;
        }
        char shifted = letters[shiftedPosition];
        return shifted;
    }
}
The result I'm getting is this:
uAnd the momerathes outgrabeuuAll mimsy were the borogrovesuDid gyre and gymble in the wabeuuTwas brillig and the sithey tovesu
How do I get rid of the u's and also separate the words by line? I have an idea of reversing the lines using a vector and using a loop counting backwards but I'm not sure how to get to there yet. Please help. Thank you.
Aucun commentaire:
Enregistrer un commentaire