-
No case for continue?
Hi guys
I am working on a assignment and It has been going ok so far but now I am stuck on what is quite an annoying problem. The code compiles and runs ok but when I enter a seat to fill, ( 1 - 5 ) it fills the seat but still displays the error message every time. I thought if I used continue to return control to the top of the loop then it would avoid the "else" message.
Here is the code - this is the function that is causing the hassle. Array pl[] has been inititalized to zero from another function.
Code:
void Airline::firstClass ( int pl[], const int SIZE )
{
int passengerTotal = 0;
const int MAX_PASSENGER = 5;
while (( passengerTotal == 0 ) || ( passengerTotal > MAX_PASSENGER ))
{
std::cout << "\nHow many passengers are flying first class? (max 5): ";
std::cin >> passengerTotal;
if ( passengerTotal > MAX_PASSENGER )
{
std::cout << "\nERROR: Max capacity for first class is 5...\n";
}
}
std::cin.ignore();
for ( int i = 0; i < passengerTotal; i++ )
{
std::cout << "\nEnter seat number for passenger " << i << ": ";
std::cin >> pl[ i ]; // read seat into array
// for each seat, increment the array element to make sure no seat is
// assgined more than once
if (( pl[ i ] == 1 ) && ( pl[ 0 ] == 0 ))
{
pl[ 0 ]++;
continue;
}
if (( pl[ i ] == 2 ) && ( pl[ 1 ] == 0 ))
{
pl[ 1 ]++;
}
if (( pl[ i ] == 3 ) && ( pl[ 2 ] == 0 ))
{
pl[ 2 ]++;
}
if (( pl[ i ] == 4 ) && ( pl[ 3 ] == 0 ))
{
pl[ 3 ]++;
}
if (( pl[ i ] == 5 ) && ( pl[ 4 ] == 0 ))
{
pl[ 4 ]++;
}
else
{
std::cout << "\nSeat is already taken, choose another...\n";
}
}
}
-
Code:
std::cin >> pl[ i ]; // read seat into array
This looks suspect to me. You are filling in values into the same array that you are using to indicate which seat you want to use.
When we get to this code, with i == 0:
Code:
if (( pl[ i ] == 1 ) && ( pl[ 0 ] == 0 ))
{
pl[ 0 ]++;
continue;
}
If you entered 1, pl[0] is not going to be zero, because pl[0] == 1 from your entry.
I think you need a temporary variable somewhere.
--
Mats
-
Thanks Mats I appriciate the help, Il see what I can do. :)
-
Also keep in mind that continue will still increment the loop counter. This means that you are going to skip the passangers that enter an incorrect number.
As for so many if-s, can't you simply do:
Code:
if (pl[user_selection - 1] == 0) {
pl[user_selection - 1] = i + 1; //taken by passanger #..
}
else {
"try again"
}