1

Following is a part of my VC++ code being coded in VS2010.

do
{

    std:: cout << "\nOPTIONS:\n";
    std:: cout << "\n1. Get all session data.\n";
    std:: cout << "\n2. Get Nth session data\n";
    std:: cout << "\n3. Get Next session data\n";
    std:: cout << "\n4. Get Previous session data\n";
    std:: cout << "\n5. Get total no of sessions\n";
    std:: cout << "\n6. Exit\n";
    std:: cout << "\nEnter Your Option: ";

    std :: cin >> option;

    switch(int(option))
    {
         case 1:
            {
                data.ReadSetupFile();
                 break;
            }

        case 2:
            {
                break;
            }

        .....
        ......

        case 6:
            {

                std::cout<<"\nARE YOU SURE YOU WANT TO EXIT?(Press y for yes and any other character for no)\n";
                cin >> opt;
                break;
            }

        default:
            {
                std::cout << "\nINAVALID OPTION!!TRY AGAIN\n";
                break;
             }

    }

    std::cout<<"\nDO YOU WANT TO CONTINUE?(Press y for yes and any other character for no)\n";
    cin >> opt;

  }while(opt=='y');

However, if I insert a character instead of an integer as value of option , the menu option is going on printed in the output console without termination until I use ctrl+c. On using this break strategy I get the message as :

First-chance exception at 0x75936da7 in SetupAPIReader.exe: 0x40010005: Control-C.

Why is the execution not terminating?

Jackzz
  • 1,417
  • 4
  • 24
  • 53
  • 1
    You pressed `Control-C` and ask why your program got a `Control-C` exception? – T.C. Sep 22 '14 at 11:00
  • Have you setup the control handler for `Ctrl-C`? – Niall Sep 22 '14 at 11:00
  • Actually my doubt is why it is not terminating? – Jackzz Sep 22 '14 at 11:02
  • Also, as to the question you probably should have asked, if `std::cin >> option;` fails, `failbit` is set on the stream and all subsequent attempt to read will simply fail; hence `opt` will never be changed. You need to [check for error, `ignore()` the invalid input, and `clear()` the error state](http://www.parashift.com/c++-faq/istream-and-ignore.html). – T.C. Sep 22 '14 at 11:02
  • @T.C. : It works properly when I supply integer value for `option`. In my logic, typecasting should convert char to integer and hence it should work properly. Isn't it? – Jackzz Sep 22 '14 at 11:08
  • @T.C.: Thank you.. it worked. Is there any significance in adding ignore()? I get the same output even if ignore is ther or not – Jackzz Sep 22 '14 at 11:22

1 Answers1

0

If the given input is not of expected type, the failbit of cin is set. Checking for this bit and clearing will reset the value to initial value of the variable.

if(!cin)
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
Jackzz
  • 1,417
  • 4
  • 24
  • 53