Modifying and Output

I'm trying to reading data from a file, which are a set of points x y. Add a third dimension, z, then out put this into a new file in the format: (x y z).
The program I wrote compiles on Ubuntu 10.04, however; the new file is created but is blank. Reading the input file works. I used the tutorials just to make it this far. I had to remove the modifying element to get this to compile. Any help is greatly appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main () {
  string line;
  ifstream myfile ("top.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      ofstream myfile ("finish.txt");
      myfile << line;
     }   
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}
By constructing the ofstream each time through the while loop, you are closing, truncating, and reopening the output
file every time through the loop. Consequently, all you will see in the output file is the last line of the input file.
Move the instantiation of myfile outside the while() loop.
You didn't make an ofstream object or output file stream object correctly. When you put it in the loop like that you constantly close, open, overwrite, and repeat.
Move line 15 under line 9 and it should be fixed.
Thank you for your replies. @JSmith the program compiles and run, but still nothing in the "finish" file. @wolfgang moving line 15 to line 9, only gives the error of conflicting declarations(won't compile).
Change the name from myfile to fout or something, and all instances of the name that write to the same name.

so
1
2
3
4
5
6
ofstream myfile ("finish.txt");
myfile << line;

// BECOMES
ofstream fout("finish.txt");
fout << line;


But still keep the change of moving it out of the loop.
Topic archived. No new replies allowed.