Write a C++ program that reads text from a file and decodes the file by subtract
ID: 3568426 • Letter: W
Question
Write a C++ program that reads text from a file and decodes the file by subtracting 4 from the ASCII value of each character. Note that the Raptor program will encode the file and the C++ program will decode it.
See chapter 12 in Starting out with C++ for information on reading and writing to text files.
Your program should:
1. Read the text file one line at a time.
2. Change each character of the string by subtracting 4 from it.
3. Write the encoded string to a second file, such as plain2.txt
Hint: In Visual Studio Express, put your coded.txt file in the project directory. The same folder that your C++ source (.cpp) file is in.
Once your program executes correctly, upload your .cpp file only. Make sure your name is on the source code in a comment
Explanation / Answer
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
// Write a C++ program that reads text from a file and decodes the file by subtracting 4 from the ASCII value of each character.
int main(){
ifstream infile("coded.txt");
ofstream outfile("plain2.txt");
if(!infile){
cout <<"unable to open file so exiting from program " << endl;
return 0;
}
string str;
while(!infile.eof()){
// 1. Read the text file one line at a time.
getline(infile, str);
// 2. Change each character of the string by subtracting 4 from it.
for(int i=0; i<str.length(); i++){
// 3. Write the encoded string to a second file, such as plain2.txt
outfile << static_cast<char> ((str[i]-4));
}
outfile << endl;
}
infile.close();
outfile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.