Hi everyone,
can someone help me plz? my program has no errors nor wornings yet it stops working and the output is all missed up :(
(in case you're wondering what it does, it's a simulator of the reader writer problem ... but it's not complete yet and i'm open to other design ideas if you have one ... please ;P )
#include <ctime> // For time()
#include <cstdlib> // For srand() and rand()
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
class Reader
{
private:
string city[5];
int tempr[5];
public:
Reader()
{
for(int i=0; i<5; i++)
tempr[i]=0;
}
void read()
{
ifstream inClientFile("record.txt",ios::in);
if(!inClientFile)
{
cerr<<"File could not be opened"<<endl;
exit(1);
}
for(int i=0;i<5; i++)
{
inClientFile>>city[i]>>tempr[i];
cout<<city[i]<<"\t\t"<<tempr[i]<<endl;
}
}
};
class Writer
{
private:
string city[5];
int tempreture;
public:
Writer(){
city[0]="Kuwait";
city[1]="Manama";
city[2]="Ryadh";
city[3]="Abu Dhabi";
city[4]="Muscat";
}
void write()
{
srand(time(0));
ofstream outClientFile("record.txt",ios::out);
if(!outClientFile)
{
cerr<<"File could not be opened"<<endl;
exit(1);
}
for(int i=0; i<5; i++)
{
tempreture = (rand() % 60) + 1;
outClientFile<<city[i]<<"\t\t"<<tempreture<<endl;
cout<<city[i]<<"\t\t"<<tempreture<<"\n";
}
}
};
int main()
{
srand(time(0)); // seeding the random generator function.
cout<<"Welcome to our reader writer simulator :)\n\nIn this simulator, 5 reading processes and 3 writer processes are operating.\n\n\n";
Reader* rdrProc[5];
Writer* wrtProc[3];
// Creating processes.
for(int i=0; i<5; i++)
{
rdrProc[i]= new Reader();
}
for(int j=0; j<3 ; j++)
{
wrtProc[i]= new Writer();
}
// let any writer process write data to the file for starter.
wrtProc[1]->write();
for(int count=0; count<20; count++)
{
int r,p;
r = ((rand() % 8) + 1);// randomly selecting a process to enter the file (1,2 & 3 are the writer processes. the rest are readers)
if(r<=3)// the process is a writer process.
{
p=(rand() % 3) + 1;
cout<<"Hi, I'm writer "<<p<<" and I wrote to the file the following data:\n";
wrtProc[p]->write();
}
else // the process is a writer process.
{
p=(rand() % 5) + 1;
cout<<"Hi, I'm reader "<<p<<" and I read the following data from the file:\n";
rdrProc[p]->read();
}
}
return 0;
}