switch case statements question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • drjay1627
    New Member
    • Nov 2008
    • 19

    switch case statements question

    how do i make sure that the switch case doesnt ternimate the program if the entry is invalid.

    in my program, if user input is y, removes the file. if user input is n, exits program, if user input is anything else prints out error message prompts for user input again and if that is a invalid input it terminates program. i dont want it to terminate the program. until the correct input is entered, it needs to prompt the user.

    Code:
    char option;
    cin >> option;
    switch (option){
    		case 'y' :
    			remove("file.txt");
    			break;
    		case 'n' :
    			exit(0);
    		default :
    			cout << "Invalid entry" << endl;
    			cin >> option;
    		}
  • drjay1627
    New Member
    • Nov 2008
    • 19

    #2
    ok i used a boolean and a while loop and fixed it but shouldnt the case statement take care of any invaild input???

    Comment

    • vmpstr
      New Member
      • Nov 2008
      • 63

      #3
      the switch statement into an infinite loop (something like while(1) or for(;;)). After you do that, the program will only terminate in the 'n' case. If you also want it to terminate in the 'y' case, you will have to put an exit there as well, or just remove the break;

      good luck

      Comment

      • vmpstr
        New Member
        • Nov 2008
        • 63

        #4
        The switch statement takes care of any cases that you explicitly specify (such as case 'y'). It also takes care of "the rest" (ie. the cases you did not explicitly specify) in the default: case.

        If you are asking whether the program should be smart enough to know what you are trying to do, the answer is no. "The program will do what you tell it to do, not what you want it to do."

        good luck

        Comment

        • drjay1627
          New Member
          • Nov 2008
          • 19

          #5
          Code:
          bool caseFlag = false;
          while(!caseFlag){
          	switch (option){
          	case 'y' :
          		remove("file.txt");
          		caseFlag = true;
          		break;
          	case 'n' :
          		caseFlag = true;
          		exit(0);
          	default :
          		cout << "Invalid entry" << endl;
          		cin >> option;
          		caseFlag = false;
          	}
          }
          this fixed it!

          Comment

          Working...