0

If I input something that my switch doesn't want to accept (I actually have 4 cases) the code will not stop for the cin>> the second time through. I had a previous version of this code call menu() right before the break; in the default case but that was also causing an finite loop. This and this and a few others have not helped me. I can't seem to tell why cin just doesn't want to get called.

void menu()
{
    bool running = true;
    int answer = 0;
    std::vector<Player> players;
    Dealer river;
    while (running) 
    {
        std::cout << "1. Start Round\t2. Add Player\t3. Remove Player\t4. Exit\n\n";
        std::cin.clear();
        std::cin >> answer;
        std::cin.ignore(std::numeric_limits <std::streamsize> ::max(), '\n');
        std::cout << answer;
        switch (answer) {
        case 1:
            //doesn't matter
            break;
        default:
            std::cout << "Invalid input.\n";
            break;
        }
    }
}
  • You need to provide a minimal complete program, because there's nothing wrong with the code you've posted. Your problem is somewhere in the code you haven't posted. I expect it's somewhere in the code you've labelled `doesn't matter`. – john Apr 30 '20 at 07:20
  • When debugging, my code never leaves this chunk and I get 0Invalid input. 1. Start Round 2. Add Player 3. Remove Player 4. Exit repeated until forever. – Captainninjakid Wright Apr 30 '20 at 07:23
  • Well since in the code you've posted `running` is always true it's no surprise that the code loops forever. But this is a different issue from the one you first asked about. – john Apr 30 '20 at 07:24
  • The only way to fix this is for you to provide complete code. There's no point in guessing where the error is. – john Apr 30 '20 at 07:26
  • The other way to do this is for you to start again and build up your code slowly, write a few lines at a time, and thoroughly test each change as you go. It takes a while for newbies to get into this habit, as they often try to do too much too quickly. – john Apr 30 '20 at 07:29
  • Have you tried putting `std::cin.ignore(std::numeric_limits ::max(), '\n');` before `std::cin >> answer;`? From what you're describing it seems you have some left over non-whitespace and non-numeric characters in your input stream, and these are being read as your next answer. This obviously fails and you get zero. This would just be a sticking plaster solution, the correct solution would be to fix the code so that this situation doesn't arise. There we go, I made a guess at your problem, even though I said I wouldn't. Can't help with the real error as I can't see that code. – john Apr 30 '20 at 07:36

0 Answers0