Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ Caesar Cipher #1342

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Caesars-Cipher/caesar-cipher.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include <iostream>
#include <string>

using namespace std;

void caesarShift(string& phrase, int shiftAmount);

int main() {

string phrase;
int shiftAmount;

// Get the shift parameters

cout << "Enter your phrase: ";
getline(cin, phrase);

cout << "Enter your shift amount: ";
cin >> shiftAmount;

caesarShift(phrase, shiftAmount);

cout << endl << phrase;

return 0;
}

void caesarShift(string& phrase, int shiftAmount) {
// Caesar Shift a certain phrase by a certain amount

int normalizedAmount = shiftAmount % 26; // Ensure that the shiftAmount keeps letters between a-z

for (int i = 0; i < phrase.length(); i++) { // Shift each letter

if (phrase[i] >= 65 && phrase[i] <= 90 && phrase[i] + normalizedAmount > 90) // Uppercase overflow
phrase[i] = phrase[i] + normalizedAmount - 26;

else if (phrase[i] >= 97 && phrase[i] <= 122 && phrase[i] + normalizedAmount > 122) // Lowercase overflow
phrase[i] = phrase[i] + normalizedAmount - 26;

else if (!(phrase[i] >= 65 && phrase[i] <= 90) && !(phrase[i] >= 97 && phrase[i] <= 122)) // Leave all non-letter characters as they are
continue;

else
phrase[i] = phrase[i] + normalizedAmount;
}
}