Re: Switch inside While loop... User error!
Cybex wrote:
I am trying to get this to work but when ever I enter an proper
integer it just hangs. The Switch default seems to catch the improper
integers but the right ones are not triggering the way I thought they
would.
Any help would be appreciated...
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare variables
int intEmpID = 0;
string strEmpName = "";
//Gather inputs
cout << "Enter the emplyee's ID: ";
cin >> intEmpID;
while (intEmpID >0) {
switch (intEmpID) {
case 1234:
strEmpName = "Sue Nguyen";
break;
This break just exits the switch stament. It does not exit the ambient while
loop.
case 1345:
strEmpName = "Janice Blackfeather";
break;
case 3456:
strEmpName = "Allen Kraus";
break;
case 4567:
strEmpName = "Margie O'Donnell";
break;
default :
cout << "Incorrect ID - Please try again" <<"\n";
cout << "Re-enter the emplyee's ID: ";
cin >> intEmpID;
} //End switch
} // End while
//display outputs
cout << "The employee ID " << intEmpID << " belongs to: " <<
strEmpName << " \n \n";
cout << "Enter the next emplyee's ID: ";
cin >> intEmpID;
return 0;
} //end of main function
Possible fixes include:
a) Use of a boolean flag.
b) Use of goto.
c) Use of a function, e.g.:
#include <iostream>
#include <string>
using namespace std;
std::string get_name ( int & intEmpID ) {
while ( true ) {
cout << "Enter the emplyee's ID: ";
cin >> intEmpID;
switch (intEmpID) {
case 1234:
return( "Sue Nguyen" );
case 1345:
return( "Janice Blackfeather" );
case 3456:
return( "Allen Kraus" );
case 4567:
return( "Margie O'Donnell" );
default :
cout << "Incorrect ID - Please try again" <<"\n";
}
}
}
int main()
{
//declare variables and get id:
int intEmpID = 0;
string strEmpName = get_name( intEmpID );
//display outputs
cout << "The employee ID " << intEmpID << " belongs to: " <<
strEmpName << " \n \n";
cout << "Enter the next emplyee's ID: ";
cin >> intEmpID;
return 0;
} //end of main function
Note that this is not totally satisfying since the function has too many
responsibilities; it looks up the string value and it issues requests for
changing the ID. It might be better to have a std::map<int,std::string>
that matches id-numbers and names and then the input validation could just
check whether that map has an entry with a given id-number.
Best
Kai-Uwe Bux