need help.

i just start to learn c++, and try to do while loop switch statement asking for user input amendment number. i don't know where to put my loop statement and how to doing loop until q is press.

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
#include "std_lib_facilities_4.h"

int main()
{
	do{

		try{	
			cout << "Which amendment?";
			char a;
			cin >> a;
			if (a > 8)
			{
				error("That is not a valid input. Please enter a number betweet 1 and 8.");
			}
			switch(a)
			{

			case'1':
				cout << "Amendment 1: Freedom of speech, the press, to form militias, of religion, and of the right to assemble." << endl;
			break;

			case'2':
				cout << "Amendment 2: The right to bear arms and form militias." << endl;		
			break;

			case'3':
				cout << "Amendment 3: You can only quarter a soldier if it's okay with the owner of the house." << endl;
			break;
			
			case'4':
			cout << "Amendment 4: A specific warrant is needed to search a house for any illegal product, or person." << endl;
			break;

			case'5':
				cout << "Amendment 5: No one can go to court without being charged by a grand jury, or be brought to court twice for committing the same crime." << endl;	
			break;
			
			case'6':
				cout << "Amendment 6: Right to fair and speedy public trial by an impartial jury" << endl;
			break;

			case'7':
				cout << "Amendment 7:" << endl;
			break;

			case'8':
				cout << "Amendment 8:" << endl;
			break;
		
			}
	}
	catch(exception& e)
	{
		cerr << "error: " << e.what()<<'\n';
		keep_window_open();
		return 1;
	}
	catch(...)
	{
		cerr << "Oops: Unknown exception!\n";
		keep_window_open();
		return 2;
	}
	}while(a != 'q');
}
Last edited on
closed account (48T7M4Gy)
One way is to wrap the while loop around the switch cases

1
2
3
4
5
6
7
8
9
10
while ( a != 'q')
{
  cin << a;

  switch()
  {
     ... including default case

  }
}


Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
    char a ; // **** moved to outside the do-while (should be visible in the while construct) *****

    do{

        try{
            cout << "Which amendment?";
            //char a; // **** moved ****
            cin >> a;

            // if (a > 8) // **** modified ****
            if( a < '1' || a > '8' ) // if a is not in [ '1' '2' '3' ... '8' ]
            {
                error("That is not a valid input. Please enter a number betweet 1 and 8.");
            }
            
            switch(a)
            {
                // rest of the code
                // ... 
closed account (48T7M4Gy)
Oops
Topic archived. No new replies allowed.