I'm doing a lesson for random access with files. They gave this pseudocode
Write a program that reads each line in a file, reverses its characters, and writes the resulting line to the same file. Use the following pseduocode:
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.
This is how i interpreted the pseudocode, which outputs the file missing the first character from the in.txt and does not reverse the letters:
while (input.get(ch))
{
pos1 = input.tellg();
here, you have skipped the first letter in your tellg; you already consumed it and moved the position one notch. use a do while maybe:
do
pos1 = ..
...
while(input.get(ch)); //here, you got the position before you moved...
you can do getline on a file same as cin, put that in a c++ string, and use c++'s tools to reverse it if that is allowed. If it is not allowed, go ahead with your letter by letter approach.
Start: 0 Size: 22 Mary had a little lamb
Start: 23 Size: 28 Its fleece was white as snow
Start: 52 Size: 29 And everywhere that Mary went
Start: 82 Size: 24 The lamb was sure to go.
Start: 107 Size: 0
pos1: 107
Program ended with exit code: 0
There are several important points:
1. The file is read line by line.
2. The line then has to be reversed.
3. The reversed line is then put back to overwrite the original line. (2 & 3 can be done as one operation)
4. There is only one single text file.