0

I have a do while loop which consists of two switch statements, some output code and some nested while loops to check for input errors. The thing is I want to break the switch statement when the user inputs 'Q' for quit and skip the rest of the code. So I've essentially got two problems.

  1. If i use a do while, then it turns into being a return 0 and a boolean flag while(true) which logically goes against itself.
  2. if i drop the do while and only use return 0, the code can't be executed multiple times.

I've come to terms with this being a flow problem rather than a syntax problem and was wondering how I should structure the flow to make it "clean code".

A quick example:

do {
    char answer;
    cout << "Type answer: ";
    cin >> answer;

    switch (answer) {
    case A:
        cout << "hello";
        break;

    case B:
        cout << "more weird output";
        break;
    case Q:
        cout << "Goodbye";
        return 0;
    }

    cout << "more useless output that I want to skip";
    cout << "how does this even work";
} while (run);

Here I've a return 0 which completely negates the need for a while(run) flag. This is bad coding practice I've been told, so I was wondering how one would go about structuring this in a good manner?

  • Change `return 0` to `run = 0`. Add `if (! run) break;` before the stuff at the bottom. See: https://stackoverflow.com/questions/10767927/loop-and-a-half-controlled – stark Oct 13 '17 at 22:04

1 Answers1

-1

Here I think i fixed the code. Make sure you are typing a capital Q not lowercase. Also you forgot ' ' around your chars. Your logic was right - just small errors :) Goodluck!

#include <iostream>

using namespace std;


int
main ()
{
  bool run = true;
  do
    {
      char answer;
      cout << "Type answer: ";
      cin >> answer;

      switch (answer)
    {
    case 'A':
      cout << "hello";
      break;

    case 'B':
      cout << "more weird output";
      break;
    case 'Q':
      cout << "Goodbye";
      return 0;
    }

      cout << "more useless output that I want to skip";
      cout << "how does this even work";
    }while (run);

  return 0;
}
D.H.
  • 186
  • 14