-2

Hi I'm playing around with basic looping techniques and I'm trying to make the following code work. When the user inputs a number other than those allowed it will go to the default where I want to give them the option to try again (without just subbing the whole code into the default) or to just exit.

#include <iostream>
using namespace std;

int main(){
    int input;
    char ans;
    cout<<"Hi please pick 1, 2 or 3: ";
    cin>> input;

    switch(input){
    case 1:
        cout<<"\nYou picked one\n";
        break;
    case 2:
        cout<<"\nYou picked two\n";
        break;
    case 3:
        cout<<"\nYou picked three\n";
        break;
    default:
        cout<<"\nYou didn't pick a valid option.\nWould you like to try again?(y/n)";
        cin>>ans;
        if(ans== 'y'){
            break;
        }else{
            continue;
        }
    }
}

When I run this I get the error that continue isn't in any loop. I'm not really quite sure how to use the continue statement. Any help with this would be greatly appreciated.

2 Answers2

2

Put your switch statement inside a loop (while(1)) or (for(;;)), then it will work.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

From http://en.cppreference.com/w/cpp/language/continue:

continue statement:

Causes the remaining portion of the enclosing for, range-for, while or do-while loop body skipped. Used when it is otherwise awkward to ignore the remaining portion of the loop using conditional statements.

You need to put the core of your function in a for loop or while loop.

bool stop = false;
while ( !stop )
{
   cout<<"Hi please pick 1, 2 or 3: ";
   cin>> input;

   stop = true;
   switch(input){
      case 1:
         cout<<"\nYou picked one\n";
         break;
      case 2:
         cout<<"\nYou picked two\n";
         break;
      case 3:
         cout<<"\nYou picked three\n";
         break;
      default:
         cout<<"\nYou didn't pick a valid option.\nWould you like to try again?(y/n)";
         cin>>ans;
         if(ans== 'y'){
            stop = false;
         }
   }
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270