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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
int get_int( std::string prompt, int min_value = 0, int max_value = 1'000'000'000 )
{
int value ;
std::cout << prompt << " [" << min_value << '-' << max_value << "]: " ;
if( std::cin >> value ) // if the user entered a number
{
if( value >= min_value && value <= max_value ) return value ;
else std::cout << "error: value is out of range. try again.\n" ;
}
else // input failure: non-numeric input
{
std::cout << "invalid input: not a number. try again\n" ;
std::cin.clear() ; // clear the failed state of stdin
std::cin.ignore( 1000, '\n' ) ; // throw away this bad input line
}
return get_int( prompt, min_value, max_value ) ;
}
void print_occupancy( const std::vector<int>& total_rooms, const std::vector<int>& occupied_rooms )
{
if( total_rooms.size() != occupied_rooms.size() )
{
std::cout << "invalid rooms information\n" ;
return ;
}
std::cout << "Floor Rooms Occupied Rooms Unoccupied Rooms % occupied Rooms\n"
<< std::fixed << std::setprecision(2) ;
for( std::size_t i = 0 ; i < total_rooms.size() ; ++i )
{
const int unoccupied_rooms = total_rooms[i] - occupied_rooms[i] ;
const double percent_occupancy = occupied_rooms[i] * 100.0 / total_rooms[i] ;
std::cout << std::setw(4) << i+1
<< std::setw(7) << total_rooms[i]
<< std::setw(12) << occupied_rooms[i]
<< std::setw(17) << unoccupied_rooms
<< std::setw(20) << percent_occupancy << '\n' ;
}
}
void run_once()
{
std::string date ;
std::cout << "date: " ;
std::getline( std::cin, date ) ;
std::string hotel ;
std::cout << "hotel: " ;
std::getline( std::cin, hotel ) ;
const int nfloors = get_int( "enter number of floors", 1, 1'000 ) ;
std::vector<int> total_rooms ;
std::vector<int> occupied_rooms ;
for( int i = 0 ; i < nfloors ; ++i )
{
std::string floor_number = std::to_string(i+1) ;
const int nrooms = get_int( "number of rooms in floor #" + floor_number, 1, 1000 ) ;
total_rooms.push_back(nrooms) ;
const int n_occupied_rooms = get_int( "number of rooms occupied in floor #" + floor_number, 0, nrooms ) ;
occupied_rooms.push_back(n_occupied_rooms) ;
}
std::cout << "stats for Hotel " << hotel << " on date " << date << '\n' ;
print_occupancy( total_rooms, occupied_rooms ) ;
}
bool run_again()
{
std::cout << "run once again (y/n)? " ;
char c ;
return std::cin >> c && ( c == 'Y' || c == 'y' ) ;
}
int main()
{
do run_once() ;
while( run_again() ) ;
}
|