|
-
August 8th, 2012, 10:43 AM
#1
Problem with reversing a string using seek/tell
Hello guys,
I have an assignment that asks me to write a program which reads all lines from a text file (one by another), reverses them and write to the same file. I also have a pseudocode with which I have to work and it is as follows:
While the end of the file has not been reached
pos1 = current get position
Read a line.
If the line was successfully read
pos2 = current get position
Set put position to pos1.
Write the reversed line.
Set get position to pos2.
I have tried many things and the code misses letters. Below you can see my code:
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
fstream file;
file.open("output.txt");
while (!file.eof())
{
int pos1 = file.tellg();
string capture;
getline (file, capture);
if (file.fail()) { return 0; }
int pos2 = file.tellg();
file.seekp(pos1);
for (int i = capture.length() - 1; i >= 0; i--)
{
string ch = capture.substr(i, 1);
file << ch;
}
file << '\n';
file.seekg(pos2);
}
file.close();
system("PAUSE");
return 0;
}
This is the text with which I have to work:
Mary had a little lamb
Its fleece was white as snow
And everywhere that Mary went
The lamb was sure to go.
And this is what I get:
bmal elttil a dah yraM
Itswons sa etihw saw eceelf
Antnew yraM taht erehwyreve d
T.og ot erus saw bmal eh
Please help me on this.
Your help is much appreciated.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|