[cs13001] Question regarding material

Mikhail Nesterenko mikhail at cs.kent.edu
Sun Sep 23 19:32:12 EDT 2012


>   I have been doing some experimentation with
> the while, and do while loops and have been very confused on how to break
> the loop.  For example if I set-up a do while loop to continue looping
> while the variable of type int the user inputs is between 1 and 3.  This
> works perfectly when the user uses the same type but, say the user messes
> up and inputs a char such as 'n' or 'g' the loop goes crazy and will keep
> looping indefinitely until I manually exit the window.  My only solution
> was to set the loop to terminate or to continue on type char and this seems
> to work if an int is accidently inserted.  My question is if there is any
> way to set the while loop to continue/terminate on type int but to take out
> the user error so this loop wouldn't indefinitely continue if the user were
> to accidently input the wrong type.

Use "break" or "continue" constructs that we studied to handle
unexpected input.  Here is an example code:


      do{
	int i;
	cout << "Input number between 1 and 3: ";
	cin >> i;
	if (i < 1 || i > 3){
	   cout >> "Incorrect input, try again\n";
	   continue;
	}
	
	// the rest of the loop code 

      }while(normal loop expression here);

Another common idiom is to wrap another loop around the input. For
example:

     do{
        int i;
	do{
	   cout << "Input number between 1 and 3: ";
           cin >> i;
	}while(i < 1 || i > 3);

       // the rest of the loop code

     }while(normal loop expression here);

Note that for this course we assume that the user always enters
correct input so you do not have to address this problem in your
programs.

Thanks,
-- 
Mikhail


More information about the cs13001 mailing list