Writting data to file

I am trying to read data from a file, test it, sort it, then write it to a file. I am able to sort the data but only the first lines that are sorted by the program are written out. How do I write all of the sorted lines into there respective files?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <fstream>
#include <string> 

using namespace std;

int main()
{
	double a,b,c,d,e,f; // aka variables
	
	void datatest(double data, double variables);
	string fail;
	double data;
	
	ifstream reader( "poem.txt" ) ;

if( ! reader )
{
cout << "Error opening input file" << endl ;
return -1 ;
}

	else
	{
	
	while (reader >> a >> b >> c >> d >> e >>f)
	{
		data = formula; // a formula used to test the data
		
	     datatest(data, variables);
	}
	}

	system("pause");
	return 0;
}

void datatest(double data, double variables) // sorts data
{ 
if (data == num)
 {
  ofstream output("file1.dat")
  output >> a >> b >> c >> d >> endl;
 }

 if (data != num)
 {
  ofstream output("file2.dat")
  output >> a >> b >> c >> d >> endl;
 }
 return;
}
Last edited on
First do this:

#include <fstream>
#include <string>
#include <iostream>
using namespace std;

int main()
{
string info = "\n\tThe Ballad of Reading Gaol" ;
info.append( "\n\t\t\tOscar Wilde 1898" ) ;

ofstream writer( "poem.txt" , ios::app ) ;

if( ! writer )
{
cout << "Error opening file for output" << endl ;
return -1 ;
}

writer << info << endl ;

writer.close() ;

return 0 ;
}
Then do this:

int main()
{
char letter ;
int i ;
// string line ;

ifstream reader( "poem.txt" ) ;

if( ! reader )
{
cout << "Error opening input file" << endl ;
return -1 ;
}
else
for( i = 0; ! reader.eof() ; i++ )
{
reader.get( letter ) ;
cout << letter ;

// getline( reader , line ) ;
// cout << line << endl ;
}

reader.close() ;

cout << "Iterations: " << i << endl ;

return 0 ;
}


Hope this helps, with the read and write part.

Last edited on
I have re-posted the example code as a full code file to help make it more clear.
Topic archived. No new replies allowed.