I need help on figuring oout exactly on how do I Write the encoded string to a s
ID: 666101 • Letter: I
Question
I need help on figuring oout exactly on how do I Write the encoded string to a second file, such as the Encrypted.txt
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string input;
fstream inputFile;
fstream outputFile("Encrypted.txt");
//Open the file in input mode.
inputFile.open("plain.txt", ios::in);
//If the file was successfully opened, continue.
if (inputFile)
{
while (inputFile) //While last read operation successful, continue
{
cout << input << endl; //Display last read line
getline(inputFile, input);//Read next line
for (size_t i = 0; i < input.size(); ++i)
{
input[i] += 4;//Adding 4 to the ASII value each character
}
}
inputFile.close();//Closes the file
}
else cout << "ERROR: File cannot be opened.";
}
Explanation / Answer
Note : if we know a file is only input/output file then it is better to open that with ifstream/ofsteam
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string input;
fstream inputFile;
//open the output file using ofstream in append mode
ofstream outputFile("Encrypted.txt", ios::app);
//Open the file in input mode.
inputFile.open("plain.txt", ios::in);
//If the file was successfully opened, continue.
if (inputFile)
{
while (inputFile) //While last read operation successful, continue
{
cout << input << endl; //Display last read line
getline(inputFile, input);//Read next line
for (size_t i = 0; i < input.size(); ++i)
{
input[i] += 4;//Adding 4 to the ASII value each character
}
//append the encrypted string to output file
if(outputFile)
outputFile << input<<endl;
}
inputFile.close();//Closes the file
}
else cout << "ERROR: File cannot be opened.";
}
OR
simply you can use the code below
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream in("input.txt"); // input
if(!in) {
cout << "Cannot open input file ";
return 1;
}
ofsteam out("Encrypted.txt",ios::app)
if(!out)
{
cout << "Cannot open input file ";
return 1;
}
while(in)
{
getline(inputFile, input);//Read next line
cout<<intput<<endl;
for (size_t i = 0; i < input.size(); ++i)
{
input[i] += 4;//Adding 4 to the ASII value each character
}
out<<input<<endl;
}
in.close();//Closes the input.txt file
out.close();//Closes encrypted.txt filefile
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.