-2

I've just started learning the basics in C++ and currently am trying to make a program that does a few basic things. The problem I have is occurring in the pasted function below.

At this point it literally does nothing when it runs. All I'm trying to do it make it so the function runs over and over again forever, until the user enters the letter 'q'.

The function must keep running even if the user enters some random string, anything, 'q' is the only keystroke that should stop the loop.

I have tried toying around with 'cin.whatever" and haven't found success. If you have an answer please provide as much explanation as possible. Thank you!

void menu()
{
    cin.clear();
    cin.ignore();
    char quit = 'w';
    while (quit != 'q') // while loop to allow the user infinite tries
    {
        cout << "Which story would you like to play? Enter the number of the story (1, 2, or 3) or type q to quit: " << endl;
        cin >> quit;

        if (quit < '1' or quit > '3') // make sure the user picks a valid choice
        {
            cout << "Valid choice not selected." << endl;
        }
        if (quit == '1')
        {
            story1(); // run story 1
        }
        if (quit == '2')
        {
            story2(); // run story 2
        }
        if (quit == '3')
        {
            story3(); // run story 3
        }
        if (quit == 'q')
        {
            cout << "good bye" << endl;
            break;
        } 
    }
}
Aiden P.
  • 29
  • 3
  • Did you try typing `q`,`[enter]` ? There's this terminal mode called "line buffering" at work. – Ben Voigt Feb 05 '18 at 21:36
  • This has made the function run, but now the issue I have is just to find a way to only make this loop end when pressing 'q'. – Aiden P. Feb 05 '18 at 21:41
  • Also regardless of what's going on extracting data from `cin`, you're mixing up integers and their character representations. `'q' > 3` and `'1' != 1` so those comparisons aren't going to do what you expect. – etheranger Feb 05 '18 at 21:47
  • What is this: `quit < 1 or quit > 3`. Did you mean `quit < '1' || quit > '3'`. You are comparing an `int` to a `char` and `or` isn't C++ syntax. – Error - Syntactical Remorse Feb 05 '18 at 21:47
  • 2
    @Error-SyntacticalRemorse: Actually, [`or` is a legal C++ equivalent to `||`](https://stackoverflow.com/q/2376448/364696). It's weird, but C++ actually made them a language feature, no includes required. – ShadowRanger Feb 05 '18 at 21:51
  • @ShadowRanger I did not know that. Good to know. Thanks – Error - Syntactical Remorse Feb 05 '18 at 21:53
  • @Error-SyntacticalRemorse Yes, check the edited code block. – Aiden P. Feb 05 '18 at 22:21

1 Answers1

0

Try adding single quotes around your 1,2,3 like you did with the q. The cin is expecting a char to be entered so evaluate it as such. e.g: if (quit == '1')

George
  • 2,101
  • 1
  • 13
  • 27
Darren B
  • 11
  • 1