I am currently working on a homework assignment where I have to create a program that will read the numbers off of a file representing a hotel's occupancy. Depending on those number I should give the user the number of floors in the hotel, the number of rooms occupied in each floor and the occupancy rate. I am stuck with getting the number of rooms occupied per floor. I believe my error is in that I must reset the number of rooms that have been accumulated. The output is only correct if the line starts with a 1 in the file line(which means the room is occupied). The 0 in the file means the room is empty and the -1 means that it is the end of the floor.
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
int main()
{
// These are the only variables you will need.
// Do not declare any more.
ifstream inFile; // the input file
int room; // 1 if the room is occupied, 0 if not, -1 if end of floor
int numOcc; // counter to keep track of the total number of occupied rooms in the hotel
int floorOcc; // counter for the number of occupied rooms on a floor
int numRooms; // counter for the total number of rooms in the hotel
int floorNum; // counter to keep track of the floor number
double occRate; // double to store the final occupancy rate
inFile.open("occupancy.txt"); // Opens the input file
numOcc = 0;
floorNum = 1;
numRooms = 0;
floorOcc = 0 ; // initialise outside the loop
// reset only when we get to a new floor
while( inFile >> room ) // loop through the input file.
{
if( room != -1 ) ++numRooms ; // a room in the hotel
if( room == 1 ) ++floorOcc ; // an occupied room on this floor
elseif( room == -1 ) // this is the end of this floor
{
// print statistics for this floor
cout << "floor# " << floorNum
<< " occupied: " << numOcc << '\n' ;
// update total number of occupied rooms in the hotel
numOcc += floorOcc ;
++floorNum ; // get to the next floor
floorOcc = 0 ; // reset count for the new floor to zero
}
elseif( room != 0 ) // must be 0 if not 1 or -1
{
cout << "error in input data: " << room << '\n' ;
return 1 ; // error return from main
}
}
if( room == -1 ) // the last entry read must have been -1
{
if( numRooms > 0 )
{
occRate = double(numOcc) / numRooms ; // avoid integer division
cout << "\nsummary:\n---------\n"
<< "total number of rooms in the hotel: " << numRooms << '\n'
<< "of which occupied rooms: " << numOcc << '\n'
<< "occupancy rate: " << occRate << '\n' ;
}
else std::cout << "unfortunately, this hotel does not have any rooms!\n" ;
}
else
{
cout << "error in input data: last entry is not -1\n" ;
return 1 ; // error return from main
}