mercredi 27 janvier 2016

Error implementing Caesar Cipher Decoder

I am trying to implement a Caesar Cipher decoder using C++. However, part of my code doesn't print anything. This is my code:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

string decypher (string line, int shift);

int main(){
    ifstream inFile;
    string filename;
    cout << "What file name? "; //Ask user for input for filename
    cin >> filename;
    inFile.open(filename);
    while (!inFile) { //If file doesn't exist, keep asking
        cout << "Bad Filename" << endl;
        cout << "What file name? ";
        cin >> filename;
        inFile.clear();
        inFile.open(filename);
    }
    int shift; //Create integer shift to hold the shift value
    while (inFile >> shift){ //Read the first element which is the shift and assign it to "shift"
        cout << "Shift: " << shift << endl;
    }
    vector <string> v;
    string line; //Create string "line" to hold each line's value
    while (getline(inFile, line)){ //Assign the line to string "line"
        string newLine = decypher (line, shift); //Assign new string "newLine" with decyphered text
        v.push_back(newLine);
    }
    for (int i = (v.size()-1); i >= 0; i-=1){
        cout << v[i] << endl;
    }

}

string decypher (string line, int shift){
    string letters = "abcdefghijklmnopqrstuvwxyz";
    string decrypted = "";
    for (int i = 0; i < line.length(); ++i){
        char ch = line[i];
        int currentPosition = letters.find(ch);
        int shiftedPosition = currentPosition - shift;
        if (shiftedPosition < 0){
            shiftedPosition = 26 + shiftedPosition;
        }
        char shifted = letters[shiftedPosition];
        decrypted += shifted;
    }
        return decrypted;
}

However, when I run the program, my decypher function isn't doing anything. What is wrong with my code? It prints the shift and thats the end of the program.

Aucun commentaire:

Enregistrer un commentaire