Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

visual studio Write a C++ program that reads text from a file and encrypts the f

ID: 3576349 • Letter: V

Question

visual studio

Write a C++ program that reads text from a file and encrypts the file by adding 4 to the ASCII value of each character. See section 5.11 in Starting out with C++ for information on reading and writing to text files. Your program should: 1. Read the provided plain.txt file one line at a time. Because this file has spaces, use getline (see section 3.8).

2. Change each character of the string by adding 4 to it.

3. Write the encoded string to a second file, such as coded.txt

4. The encoded file should have the same structure as the original file, if the second line of the original file has 24 characters (including spaces) then there should be 24 characters on the second line of the encoded file (spaces will now look like '$')

plain .txt

Explanation / Answer

#include <string>

#include <iostream>

#include <fstream>

#include <limits>

using namespace std;

int main()

{

//input and output file names.These are placed in the same project folder,else mention the entire path

   string inputFileName = "plain.txt" ;

   string outputFileName = "coded.txt" ;

// the maximum number that can represent all values of char

//unsigned if the int ==1 then it would result in an implementation-defined result which wouldn't be value preserving

unsigned int maxVal = numeric_limits<char>::max() ;

int new_line = ' ' ; // value of the new-line character

int extra = 4 ; // value to be added to each char

//inputFile for reading

ifstream inputFile(inputFileName) ;

//each line of the input file

string line ;

// ouputFile for writing

ofstream ouputFile(outputFileName) ;

// to read the file per line

while(getline( inputFile, line ) )

{

for( char& ch : line ) // to read through each character of the line

{

int newValue = ch + extra ; // new value generated by adding 4 for each character

if( newValue < maxVal && // new value is within range

       newValue != new_line ) // and won't result in a spurious new line

{ ch = newValue ; } // update the character in the line with the new value

else {

   cout << "Error:Character cannot be changed";

}

}

// write the modified line to the output file and append the newLine character

ouputFile << line << ' ' ;

}

inputFile.close();

ouputFile.close();

}