helppp in reading and writing files

after reading and writing a file I don't know if this code is correct

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string Name="";
string capac="";
bool openFile (ifstream & inFile);
class Location {
public:
string locationName;
int storageCap;
//default constructor
Location ()
{
locationName="";
storageCap=0;
}
//assignment operator
Location (string name, int capacity)
{
locationName = name;
storageCap = capacity;
}
};
//code to open the file
bool openFile (ifstream & inFile)
{
inFile.open ("locations.txt");
if (! inFile.is_open())
{
cout<<"Open file operation failed!"<<endl;
return false;
}
else
{
cout<<"Open file operation succeeded!"<<endl;
return true;
}
}
//code to read the file
typedef enum state {start_state, within_name, end_name, within_capacity, end_capacity, Error};

state current = start_state;
Location object[1024];
int i=0;
bool readFile( ifstream & readSurvey)
{

char c='\0';
while (! readSurvey.eof())
{
readSurvey.get(c);
if (current == start_state)
{
if (isalpha (c) !=0)
{
Name=Name+c;
current= within_name;
}
else
{
current= Error;
}
}
else if (current== within_name)
{
if (isalpha (c)!=0 || c==' ')
{
Name= Name +c;
}
else if (c==':')
{
object[i].locationName= Name;
Name="";
current= end_name;
}
else
{
current= Error;
}
}
else if (current==end_name)
{
if (c=' ')
{
current= end_name;
}
else if (isdigit(c)!=0)
{
capac= capac+c;
current= within_capacity;
}
else
{
current = Error;
}
}
else if (current= within_capacity)
{
if (isdigit (c) !=0)
{
capac= capac+c;
}
else if (c=' ')
{
current= end_capacity;
}
}
else if (current== end_capacity)
{
int b= atoi(capac.c_str());
object[i].storageCap= b;
b=0;
i=i+1;
while (c!='\n')
{
readSurvey.get(c);
}//to skip cube meters
}
}
cout<<i<< c<<endl;
if (current= Error)
{
cout<<false;
return false;
}
readSurvey.close();//closing file
return true;
}
//compute total

int totalcal ()
{
int num=0;
int sum=0;
while (num<i)
{
sum = sum+ object[num].storageCap;
num=num+1;
}
return sum;
}
int totalcal ();
int main ()
{
ifstream infile;
openFile(infile);
bool read= readFile(infile);
if (read== true)
{
cout<<i;
int s= totalcal ();
cout<<s;
return 0;
}
else
{
return -1;
}

}52
Last edited on
Topic archived. No new replies allowed.