90.0k views
4 votes
Write a C++ program that will go through the first step of encrypting an input file and writing the encrypted contents to an output file. For each letter read in from the input file, add 3 letters to the value of the input letter. If the input letter is an A, then the encrypted letter would be a D. If the input letter from the input file is an X, then the encrypted letter would be an A. All spaces, digits, punctuation, and special characters do not need to be encrypted at this level. Simply write the space, punctuation, or special character to the output file as is. If a letter is uppercase in the input file, it should remain as an uppercase character in the output file. If a letter is lowercase in the input file, it should remain as a lowercase character in the output file.

1 Answer

3 votes

Final answer:

The provided C++ program reads characters from an input file, encrypts letters by shifting them forwards three positions in the alphabet, and outputs the encrypted content to another file. Non-alphabetic characters remain unchanged, and the case sensitivity of the letters is preserved.

Step-by-step explanation:

Simple C++ File Encryption Program

The task is to write a C++ program that performs a simple encryption on a text file. This program should read characters from an input file, encrypt alphabetic characters by shifting them three positions forward in the alphabet (with wrap-around), and write the result to an output file. Non-alphabetic characters will be written to the output file as is, and the case of the letters will be preserved.

Here is an example of a C++ program that can accomplish this:

#include
#include
#include

using namespace std;

int main() {
ifstream inputFile("input.txt");
ofstream outputFile("output.txt");

if(!inputFile.is_open() || !outputFile.is_open()) {
cerr << "Could not open files!" << endl;
return 1;
}

char ch;
while(inputFile.get(ch)) {
if(isalpha(ch)) {
char base = isupper(ch) ? 'A' : 'a';
ch = (ch - base + 3) % 26 + base;
}
outputFile << ch;
}

inputFile.close();
outputFile.close();
cout << "Encryption complete." << endl;

return 0;
}

Make sure to handle the file stream exceptions appropriately, and replace "input.txt" and "output.txt" with the actual file names you want to work with.

User Mg Bhadurudeen
by
7.1k points