while loop using char

Oct 9, 2009 at 5:43am
Total Noob here, but I'm having a bit of a problem using the while loop using characters.. Can anyone point out my fatal flaw?

char ChooseStack()
{
char choice;
while (choice != 'A' || choice != 'B' || choice != 'C')
{
cout << "Which stack do you want to choose from ('a', 'b', 'c') ? ";
cin >> choice;
switch (choice)
{
case 'a':
case 'A': choice = 'A';
break;
case 'b':
case 'B': choice = 'B';
break;
case 'c':
case 'C': choice = 'C';
break;
default: cout << "Invalid choice." << endl;
}
}
return choice;
}
Oct 9, 2009 at 5:54am
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;
}
Oct 9, 2009 at 5:56am
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.
Oct 9, 2009 at 6:00am
You can use a boolean to see if the choice is good (i.e. goodChoice)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    bool goodChoice;

    while (!goodChoice)
    {
    std::cout << "Which stack do you want to choose from ('a', 'b', 'c') ? ";
    std::cin >> choice;
    switch (choice)
    {
        case 'a':
        case 'A': choice = 'A';
                  goodChoice = true;
                    break;
        case 'b':
        case 'B': choice = 'B';
                  goodChoice = true;
                    break;
        case 'c':
        case 'C': choice = 'C';
                  goodChoice = true;
                    break;
        default: std::cout << "Invalid choice." << std::endl;
        }


P.S. [c0de]...[/c0de] (code) is better for code input than quotes.
Last edited on Oct 9, 2009 at 6:04am
Oct 9, 2009 at 6:06am
AHHH! Thanks so much bluezor!! That makes a lot of sense!
Topic archived. No new replies allowed.