In: Computer Science
Please write this code in C++, also if you could please bold the names of the input files and provide comments for each choice.
For this part, the program gives the user 4 choices for encrypting (or decrypting) the first character of a file. Non-lowercase characters are simply echoed. The encryption is only performed on lowercase characters.
This is the input files named file1.txt and file2.txt
yippee
A-bba cc xyyz
This is what the user is typing it's in bold, and the output is under it.
Sample Run #1 (bold, underlined text is what the user types):
? 1 file1.txt y
Sample Run #2 (bold, underlined text is what the user types):
? 2 file1.txt b
Sample Run #3 (bold, underlined text is what the user types):
? 3 file1.txt v
Sample Run #4 (bold, underlined text is what the user types):
? 4 file1.txt 21
Sample Run #5 (bold, underlined text is what the user types):
? 1 file2.txt A
Sample Run #6 (bold, underlined text is what the user types):
? 2 file2.txt A
Sample Run #7 (bold, underlined text is what the user types):
? 4 file2.txt 0
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int choice; // stores user choice of encryption
string fileName; // stores filename
// prompting user
cout << "? ";
cin >> choice >> fileName;
// opens the file
ifstream inFile;
inFile.open(fileName.c_str());
char c; // character from file
inFile.get(c); // reading first character from
file
bool lower = islower(c); // if it's lowercase
char c_new;
if (choice == 1) // if user chooses print
character
{
// printing first character
cout << endl << c
<< endl;
}
else if (choice == 2 && lower) // if user
chooses to shift forward and character is lowercase
{
c_new = (((int)c - 97) + 3)%26 +
97;
cout << endl << c_new
<< endl;
}
else if (choice == 3 && lower) // if user
chooses to shift backward and character is lowercase
{
if (c > 'c')
{
c_new = (((int)c
- 97) - 3)%26 + 97;
}
else if (c == 'a')
{
c_new =
'x';
}
else if (c == 'b')
{
c_new =
'y';
}
else
{
c_new =
'z';
}
cout << endl << c_new
<< endl;
}
else if (choice == 4 && lower) // if user
chooses to print last two digits of ascii value
{
cout << endl <<
(int)c%100 << endl;
}
else if (choice == 4 && !lower) // if
character is upper case
{
cout << endl << 0
<< endl;
}
else // if character is upper case
{
cout << endl << c
<< endl;
}
// closing file
inFile.close();
return 0;
}
OUTPUT: