1

以下是我在 VS2010 中编写的 VC++ 代码的一部分。

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');

但是,如果我插入一个字符而不是一个整数作为 的值option,则菜单选项将继续打印在输出控制台中而不会终止,直到我使用ctrl+c. 在使用这种中断策略时,我得到的消息是:

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

为什么执行没有终止?

4

1 回答 1

0

如果给定的输入不是预期的类型,则设置failbitof cin。检查该位并清除会将值重置为变量的初始值。

if(!cin)
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
于 2014-09-22T11:25:39.577 回答