-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcipher.cpp
90 lines (78 loc) · 1.7 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <cctype>
using namespace std;
string encode(string text) {
string result;
for (int i = 0; i < text.length(); i++) {
if (isalpha(text[i]))
text[i]++;
if (text[i] >= 'a') {
if (text[i] > 'z')
text[i] -= 'z' - 'a' + 1;
}
else if (text[i] >= 'A')
{
if (text[i] > 'Z')
text[i] -= 'Z' - 'A' + 1;
}
result += text[i];
}
return result;
}
string decode(string text) {
string result;
for (int i = 0; i < text.length(); i++) {
if (isalpha(text[i]))
text[i]--;
if (text[i] >= 'A' && text[i] <= 'Z')
{
if (text[i] < 'A')
text[i] -= 'A' - 'Z' - 1;
}
else if (text[i] < 'a'&& text[i]!=' ')
text[i] -= 'a' - 'z' - 1;
result += text[i];
}
return result;
}
int main(int argc, char* argv[]) {
string fileContent;
string fileName = argv[1];
string flag = argv[2];
char letter = tolower(argv[3][0]);
if (flag[0] != '-')
{
cout << "[ERROR] Invalid flag. Use -e for (e)ncoding or -d for (d)coding ";
return 0;
}
if (!isalpha(letter) || strlen(argv[3]) > 1)
{
cout << "[ERROR] Invalid argument <";
cout << argv[3] << ">" << endl;
cout << "<letter> must match A-Z or a-z";
return 0;
}
ifstream file(fileName);
if (!file.is_open())
{
cout << "[ERROR] Failed to open <" << fileName << ">" << endl;
return 0;
}
while (file.good())
{
getline(file, fileContent);
}
if (letter == tolower('A'))
cout << fileContent;
else if (letter == tolower('B') && (flag.substr(1) == "e" || flag.substr(2) == "e"))
{
cout << encode(fileContent);
}
else if (letter == tolower('B') && flag.substr(1) == "d") {
cout << decode(fileContent);
}
}