I’m having a few problems correctly implementing a C++ switch statement within a while loop.
I’m testing for the char ‘0’, yet when I press this key on my keyboard and hit enter, the loop still continues.
Why would this be? Could it be something to do with my keyboard or ASCII set or something along those lines?
Here is my source:
#include "Character.h"
using namespace std;
int main()
{
char tmp;
Character* kite;
kite = new Player();
////////////////////////////
// Name
////////////////////////////
cout << "\n\t\tPlease enter your name:\n\t\t";
cin >> tmp;
kite->setName(tmp);
////////////////////////////
// Weapon
////////////////////////////
cout << "\n\n\t\tPlease select your weapon of choice:\n";
const int MAXITEMS = 3;
string lastItem;
string inventory[MAXITEMS] = {"Sword", "Staff", "Double Blades"};
string replaceItem;
string addItem;
// Print what is in inventory to start with
for (int i = 0; i < MAXITEMS; i++)
{
lastItem = inventory[i];
cerr << "\t\t" << i << ") " << inventory[i] << endl;
}
bool done = false;
char choice;
cin >> choice;
while (!done)
{
switch (choice)
{
case '0':
kite->setWeapon(inventory[1]);
done = true;
break;
}
if (done) //I added this in lately to try to overcome issue
{
break;
}
}
return 0;//exit code
}
You are not setting
choiceinside your loop.Your code only reads
choicebeforehand, so if the first (and only) character it reads is'0', it will exit on the first iteration. However, if your first character is not'0', it will not read anything else, it will just run forever.If your program is hanging, I suspect it is getting some character that is not
'0'. You can verify/debug this by checking (via debugger or printing) what the actual value ofchoiceis in the loop.