The assignment is to write a C++ program which will do the following: 1) prompt
ID: 641392 • Letter: T
Question
The assignment is to write a C++ program which will do the following:
1) prompt the user for the encryption key (number from 1 to 26)
2) if the input value is not between 1 to 26 inclusive, then display "Invalid key, Try again." and prompt the user until a valid value is provided.
3) when a valid key is entered, then
a) open input file named "message.txt"
b) loop through each character
1. If the upper case representation of the current character is not between 'A' and 'Z', then skip that character
2. else
a. apply the Caesar Cypher encryption to the current character (i.e. offset the char by the key value provided by the user)
NOTE: if new char is > 'Z', then wrap around to beginning of alphabet. example: 'W' with an encryption key of 7 would be 'D'; 'Z' with an encryption key of 1 would be 'A', etc.
b. output the encrypted character to screen
Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int key;
while(true){
cout << "Enter encryption key: ";
cin >> key;
if(key < 1 || key > 26){
cout << "Invalid key, Try again." << endl;
}
else{
break;
}
}
ifstream in;
char ch;
in.open("message.txt");
if(in.is_open()){
while(in >> ch){
if(ch >= 65 && ch <= 90){
if(ch + key > 90){
ch = (64 + (ch + key - 90));
}
else{
ch += key;
}
cout << ch;
}
}
cout << endl;
}
else{
cout << "Can not open the file" << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.