-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCipher.cpp
71 lines (56 loc) · 1.35 KB
/
Cipher.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//______________________________________________________________________________
//
// Cipher
//
// This class prompts the user for a string and a key.
// The given string is the encoded using the given key.
//
#include <iostream>
#include <string>
using namespace std;
string encode(string, int);
int main()
{
// Get values from user and print encoded string.
// Create variables
string str;
int key;
// Get string from user.
cout << "String to encode: ";
getline(cin, str);
// Get key from user.
cout << "Key to encode with: ";
cin >> key;
// Print the encoded string.
cout << encode(str, key) << "\n";
system("pause");
return 0;
}
// Encode the given string using the given key.
string encode(string str, int key)
{
// Encode the given string with the given key.
string newStr = "";
for (int i = 0; i < str.length(); i++) {
char c = str[i];
// Check if the given character is alpha
if (isalpha(c)) {
// Record whether or not the character is uppercase.
bool upper = isupper(c);
// Convert the character to lowercase for easier calculations.
c = tolower(c);
// Encode the character.
c = (((c - 97) + key) % 26) + 97;
// Put the character into its beginning case.
if (upper) {
newStr += toupper(c);
} else {
newStr += c;
}
} else {
newStr += c;
}
}
// Return the encoded string.
return newStr;
}