Save/Write to a file

I have written this program and I would like to save/write to a file but the weights and values are not being written to the file. Can I get some help? Thanks!

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

const int lag=10000;

int ebo(int,int);
int maximum(int,int);

int value[lag],
weight[lag],
v[lag][lag],
x[lag];

int i,
j,
m,
n;

int ebo(int i,int j)
{
int val;
if(v[i][j]==-1)
{
if(j<weight[i])

val=ebo(i-1, j);

else val=maximum(ebo(i-1, j),(ebo(i-1, j-weight[i])+value[i]));
v[i][j]=val;
}
return v[i][j];
}

void svector()
{
int k;
k=m;
for(int i=n; i>=0; i--)
{
if(v[i][k]!=v[i-1][k])
{
x[i]=1;

k=k-weight[i];
}
}
for(int i=1; i<=n; i++)
{
cout<<"(";

for(i=1; i<=n; i++)

cout<<x[i]<<","<<" ";

cout<<")";
}
}

int maximum(int a, int b)
{
return (a>b)?a:b;
}

//
int main()
{

int f,
W;
cout<<"Please enter no. of items:\nn = ";
cin>>n;

cout<<" \n"<<endl;
cout<<"Subset data instance for the 0-1 KP:\n"<<endl;

cout<<"weight"<<setw(9)<<"value"<<endl;
cout<<"________________"<<endl;

srand(time(0));
for(int i=1; i<=n; i++)
{
weight[i] = rand() % 100 + 1; // 1<=w<=100
value[i] = weight[i]; // 1<=v<=100

cout<<setw(3)<<weight[i]<<setw(10)<<value[i]<<endl;

}

cout<<"\n"<<endl;

cout<<"Generate total weight capacity of knapsack: ";
int total = 0 ;
for(int i = 0; i<=n; i++)
{
total = total + weight[i];
}
m = total/2;
cout<<"W = "<<m<<endl;

cout<<"\n"<<endl;

for(int i=0; i<=m; i++)
v[0][i]=0;
for(int i=0; i<=n; i++)
v[i][0]=0;
for(int i=1; i<=n; i++)

for(int j=1; j<=m; j++)

v[i][j]=-1;

f=ebo(n, m);

cout<<"The optimal value is: "<<f<<endl;

cout<<" "<<endl;

cout<<"The optimal soluton is: ";

for(int i=1; i<=n; i++)
x[i]=0;
svector();

fstream myfile;
myfile.open ("subset-sum.txt");
myfile<<"Subset-Sum Data Instance for 0-1 KP\n\n";
myfile<<"no. of items: "<<n<<"\n"<<endl;
myfile<<"weight capacity of knapsack: "<<m<<"\n"<<endl;
myfile<<"weight"<<setw(10)<<"value"<<endl;
myfile<<"________________"<<endl;

srand(time(0));

for(int i=1; i<=n; i++)
{
weight[i] = rand() % 100 + 1; // 1<=w<=100
value[i] = weight[i]; // 1<=v<=100
}
myfile<<setw(3)<<weight[i]<<setw(10)<<value[i]<<endl;
myfile<<"optimal value is: " <<f<<"\n\noptimal solution is: "<<x[i]<<endl;
myfile.close();

system("pause");

return 0;
}
next time use code tags

http://www.cplusplus.com/doc/tutorial/files/
covers pretty much everything you need to know
Topic archived. No new replies allowed.