C++ do while loop ensure user types a correct response

Introduction

The format of the do-while is

do
{
   block of one or more C++ statements;
} while (test expression)

Input routine to ensure user types a correct response.


#include <iostream>
using namespace std;
int main()//from   ww  w . ja  v a2  s . c  om
{
   char ans;
   do
   {
      cout << "\nYou must type a Y or an N\n";   // Warn and ask
      cout << "Do you want to continue (Y/N) ?"; // again.
      cin >> ans;
   }            // Body of while loop    ends here.
   while ((ans != 'Y') && (ans != 'N'));
   return 0;
}



PreviousNext

Related