I am trying to write a program in C++ that will read a file, then output into a
ID: 3547691 • Letter: I
Question
I am trying to write a program in C++ that will read a file, then output into a new file in ASCII +5. The input file has 4 lines. My problem is I can't get the output to have 4 lines. It just has one line. Here is my program. How do I get it to output each line after it converts the text to ASCII +5?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
char ch;
fstream inputFile, outputFile;
inputFile.open("plain1.txt", ios::in);
outputFile.open("plain.txt", ios::out);
while (!inputFile.eof())
{
inputFile.get(ch);
outputFile.put(ch+5);
}
inputFile.close();
outputFile.close();
return 0;
}
Explanation / Answer
The only problem with your code is that it also prints the ascii value of ' ' as ' '+5, which is not a new line character. So, if you want the output to be in 4 seperate lines just like in the input, you need to add 5 to the charcters that are not ' '.
Thus, you need to make an exception for the ' ' case, where you print it as it is.
Modified Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
char ch;
fstream inputFile, outputFile;
inputFile.open("plain1.txt", ios::in);
outputFile.open("plain.txt", ios::out);
while (!inputFile.eof())
{
inputFile.get(ch);
if(ch==' ')
{
outputFile.put(ch);
}
else
{
outputFile.put(ch+5);
}
}
inputFile.close();
outputFile.close();
return 0;
}
The above is the required modified code. Hope this helps you.
Comment for any more doubts.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.