Invalid Inputs in Switch and If statements.

closed account (z1AqoG1T)
I'm writing a program where there are switch and if statements. The characters that the statements require in order to proceed are either F,I,A (and their lowercase counterparts).

When the user inputs something invalid, say the character S, how do I terminate the program?
You should "terminate" the program by designing the logic flow to reach the end of main(). That is the proper way to end a 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
// Example program
#include <iostream>
#include <string>

int main()
{
    char ch = 'X';
    
    std::cout << "Enter F, I, or A to continue: ";
    std::cin >> ch;
    
    bool good = false;
    
    switch (ch) {
      case 'F':
      case 'f':
        good = true;
        break;
      case 'I':
      case 'i':
        good = true;
        break;
      case 'A':
      case 'a':
        good = true;
        break;
      default:
        good = false;
    };
    
    if (good)
    {
        std::cout << "Good!\n"; 
        
        // do another stuff
    }
    else
    {
        std::cout << "Bad! Program over = very yes.\n";   
    }
}
Last edited on
Topic archived. No new replies allowed.