Switch Statement, Repeat Prev Code.

I am very new to C++ and I was working on making a extremely basic calculator. Although there is one thing I cant figure out.

Lets say a user puts "1" into the program to select "Addition". After he has put that of course it will check if its greater than 5. And if its not it will run Case 1.

But after the user has gotten their result how would I make the program go back to the initial menu. instead of closing?

If I don't use a break the program runs the rest of the cases but if I do it stops and closes. I know this is an extremely nooby question but all help is appreciated, thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  int main()
{
    int R;

    cout << "Select a Function 1-5" << endl;
    cout << "1 - Addition" << endl;
    cout << "2 - Subtraction" << endl;
    cout << "3 - Division" << endl;
    cout << "4 - Multiplication" << endl;
    cout << endl;

    cin >> R;

    cout << endl;

    if(R > 5){
        cout << "Please select an option listed." << endl;
};
    switch(R){
    case 1:
        int a;
        int b;
        int c;

            cout << "What numbers would you like to add?" << endl;
            cin >> a;
            cin >> b;
            cout << endl;

            c = a + b;

            cout << endl;
            cout << "Your Result is: " << c << endl;

            break;

    case 2:
            int Aa;
            int Bb;
            int Cc;

            cout << "What numbers would you like to subtract?" << endl;
            cin >> Aa;
            cin >> Bb;
            cout << endl;

            Cc = Aa - Bb;

            cout << endl;
            cout << "Your Result is: " << Cc << endl;

            break;
The solution is loop. See http://www.cplusplus.com/doc/tutorial/control/

You have now:
1
2
3
4
int main()
{
  // code that you want to repeat
}


With loop:
1
2
3
4
5
6
7
8
9
int main()
{
  bool condition = false;
  do {
    // code that you want to repeat

    // update condition
  } while ( condition );
}


The do .. while executes its "body" at least once. That seems appropriate for your case.

You have to update the condition inside the loop.
a few additional things...
I feel it is not good practice to define local variables inside switch statements. Their scope can be tricky to manage correctly, and the code frustrating to read.

you appear to have discovered some of these problems because int Aa looks like a fix :)

I would put a,b, and c right above the switch statement. If you want to confine them to the switch statement, an extra set of {} would scope them only to the switch.. looks like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{   //extra / scope bracket
     int a,b,c;
   switch(..) 
      ..
    case(..)
        //use a,b,c
     break
  case ... 
     //use a,b,c differently
    break
   etc.

} // end scoping bracket

  a = 3 ; //a is out of scope here, compiler complains, so a is confined. 

also switches should have a default case.
default: cout << "invalid input\n" ; //whatever you want to do about it here

What you have will work, but these ideas will help when you have larger scale programs.
I'm struggling unbelievably hard to implement this. Ive even watched Bucky's guides on loops several times. I just can't get it.
For example, here the user updates the condition on line 12:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int main()
{
  int R = 0;

  do {
    cout << "Select a Function 1-5" << endl;
    cout << "1 - Addition" << endl;
    // ...
    cout << "5 - Quit" << endl;
    cout << endl;

    cin >> R;
    cout << endl;

    int a = 0;
    int b = 0;
    int c = 0;
    switch (R) {
    // cases
    default:
      cout << "Please select an option listed." << endl;
    }
  } while ( R != 5 );

  return 0;
}
Hi ggxgank,
Just a word of practice... you will probably encounter a lot of case where you will need a "switch". You're still learning so it's ok to experiment.
Just note that "switch" is a bad smell and you will learn of lot (about good code) if you always try to look for the reason why the switch "is necessary" and try to replace it by other things.

For example here, don't be afraid to chain 5 "if" ^_^.
Also, take the habit to use functions ;o) and good names like :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
int readNumber()
{
	int number;
	std::cin >> number;
	return number;
}

int doAddition()
{
	int a = readNumber();
	int b = readNumber();
	return a + b;
}

int main()
{
	using namespace std;
//--
	for(auto keepGoing = true; keepGoing;)
	{
		cout << endl << "Select a Function 1-5" << endl;
			cout << "1 - Addition" << endl;
			cout << "2 - Subtraction" << endl;
			cout << "3 - Division" << endl;
			cout << "4 - Multiplication" << endl;
			cout << "5 - quit ^_^" << endl;
		int const operation = readNumber();
		if(1 == operation)
		{
			int const result = doAddition();
			std::cout << "Your Result is " << result << std::endl;
		}
		else if(2 == operation)
		{
			...
		}
		...
		else if(5 == operation)
		{
			keepGoing = false;
		}
		else
		{
		}
	}
//--
	return 0;
}

You will see more clearly the structure of your process. The refactoring will then be easier.

Not a thing to do, but you can eliminate the succession of "if" that looks too much like a kind of "switch" by using a table of functions : it's "simple" since you already use a number to indicate the operation you want to execute...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>

int readNumber()
{
	int number;
	std::cin >> number;
	return number;
}

int doAddition()
{
	return readNumber() + readNumber();
}

int doSubtraction()
{
	return readNumber() - readNumber();
}

int doMultiplication()
{
	return readNumber() * readNumber();
}

int doDivision()
{
	return readNumber() / readNumber();
}

typedef int (operationFunction)();

int readOperation()
{
	using namespace std;
	cout << endl << "Select a Function 1-5" << endl;
		cout << "1 - Addition" << endl;
		cout << "2 - Subtraction" << endl;
		cout << "3 - Division" << endl;
		cout << "4 - Multiplication" << endl;
		cout << "5 - quit ^_^" << endl;
	return readNumber();
}

int main()
{
	operationFunction const* const doOperation[5] = { nullptr, doAddition ,doSubtraction, doMultiplication, doDivision };
	for(auto keepGoing = true; keepGoing;)
	{
		int const operation = readOperation();
		if((1 <= operation) && (operation <= 4))
		{
			int const result = (*doOperation[operation])();
			std::cout << "Your Result is " << result << std::endl;
		}
		else if(5 == operation)
		{
			keepGoing = false;
		}
		else
		{
			std::cout << "Game over man !" << std::endl << std::endl;
		}
	}
//--
	return 0;
}

The "function pointers" thing is given only as an example of how to get rid of a switch, it is not to do per say. I find that a bit C-ish and ugly, but it's a lot better than a switch especially if your "routing" functionality use a simple integer to dispatch the operation.

You can see that the refactoring into functions make the code a lot easier to read but also to maintain because now, you have four operations that do exactly the same except for the computation part.
And this is what we expect somehow of a calculator... because then, you can add any two-infix-operand operation you want, just the same way ^_^
Note also that you don't have anymore all of those local variable that polluted your code... especially in a switch --> read more about local variable in a switch ;o)

Have fun :oP~
Last edited on
Ok I am finally back. My code is extremely messy but now at least it works. Get it working first, then work on making it look nice :D

I'm going to post my full program so I'm going to use pastebin.com because it's pretty big and messy.

https://pastebin.com/2C5dbVxH

** I also know that using the sleep function is unique to the Windows OS only.

** Also @punksheep, some of the code you gave me wouldn't work and spat out errors I wasn't exactly sure how to fix. For the "auto" part it said it wasn't the same in C++ 11 or something and that I should remove it and the

int const calculation == readNumber();

needed to be changed to

int const calculation = readNumber();

I am so grateful for your help and I want to say thank you. It really really helped.


Last edited on
Another way to structure the program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

const int ADD = 1;
const int SUB = 2;
const int DIV = 3;
const int MUL = 4;
const int QUIT = 5; 

int readNumber(const string& prompt) 
{
  cout << prompt;
  int number;
  cin >> number;
  return number;
}

void show_menu()
{
  cout << "\nSelect a Function 1-5" << endl;
  cout << "1 - Addition" << endl;
  cout << "2 - Subtraction" << endl;
  cout << "3 - Division" << endl;
  cout << "4 - Multiplication" << endl;
  cout << "5 - Quit" << endl;
}

int main()
{
  while (true)
  {
    cout << "Welcome at my calculator." << "\n";
    int op1 = readNumber("\nEnter first number: ");
    int op2 = readNumber("\nEnter second number: ");
    show_menu(); 
    int choice = readNumber("\nEnter operation: ");
    int result = -1;

    switch (choice)
    {
      case ADD: 
        result = op1 + op2;
        break;
      case SUB:
        result = op1 - op2;
        break;
      case MUL:
        result = op1 * op2;
        break;
      case DIV:
        result = op1 / op2; // TO DO check for division by 0
        break;
      case QUIT:
        cout << "\nThanks for using. Good bye\n";
        return 0;
      default:
        cout << "\nIllegal choice - choice must be between 1 and 5\n";
        break;
    }
    if (choice >= 1 && choice <= 5)
    {
      // output only for a valid operation
      cout << "Result = " << result << "\n";
    }
    Sleep(3000);
    system("cls");
  }
}

As someone who is new to coding its amazing seeing that one simple thing can be written a million ways. Although I'm guessing you will always want to go for the most optimised/cleanest code. :D

Right now I'm working on a small cheat/trainer for Stardew Valley, it won't be anything heavy just modifying some values here and there :3

Topic archived. No new replies allowed.