Kinda ghetto rigged it, with an integer.. but any help with a better solution, would be so appreciated.. (I looked for another example on here, but couldn't find it.)
char ChooseStack()
{
char choice;
int n = 0;
while (n == 0)
{
cout << "Which stack do you want to choose from ('a', 'b', 'c') ? ";
cin >> choice;
switch (choice)
{
case 'a':
case 'A': choice = 'A'; n = 1;
break;
case 'b':
case 'B': choice = 'B'; n = 1;
break;
case 'c':
case 'C': choice = 'C'; n = 1;
break;
default: cout << "Invalid choice." << endl;
}
}
return choice;
}
Hello,
First of all, please get in the habit of indenting your code when appropriate, it makes it more readable.
Secondly you are declaring a variable, choice, without giving it any value. When you do this the variable you declare in not created 'empty' as you might expect but instead contains some random value which you don't know, referred to as 'garbage'.
For this reason you can (it's syntactically correct) but you should never (it's unpredictable) test a variable containing garbage value.
Your code allows the while loop to start only when choice is different from A B or C. For all you know choice could contain exactly those value and thus terminate your program.
I suggest you move the cout and cin lines outside the while loop.