Input/Output with files problem

I am stuck on a problem where I have to replace the sentence from a text file with the reversed version of the sentence. I can make the reversed sentence display on the screen but I'm not sure how to replace it and save it in the text file. This is what I have so far:

#include <iostream>
#include <fstream>	

using namespace std;

int main()
{
	char sentence[50]; // sentence from Text1.txt file
	int length; // number of characters in sentence
	int i; // array variable

	ifstream infile("c:/Text1.txt", ios::in);

	if (!infile) 		
	{
		cerr << "File Text1.txt cannot be found" << endl;
		exit(1);
	} 				
	
	infile.getline(sentence, 50); // retrieves sentence from Text1.txt
	cout << endl << "File Text1.txt has the following sentence: " << sentence << endl;
	infile.close(); // closes the file
	
	cout << "The reversed sentence of Text1.txt is: ";
	
	for (i = length - 1; i >= 0; i--)
		cout << sentence[i]; // displays reversed sentence
	cout << endl << endl;



Last edited on
The nice thing about C++ streams is that they all work the same.
So instead of sending the reversed sentence to cout, send it to your file.

To do that, you'll have to close the file, then re-open it to rewrite:
1
2
3
4
5
6
7
8
9
infile.close();

ofstream outfile("C:/Text1.txt", ios::out | ios::trunc );
...
for (i = length - 1; i >= 0; i--)
        outfile << sentence[i];
outfile << endl << endl;

outfile.close();

Hope this helps.
Thank you so much.
Topic archived. No new replies allowed.