Do-While循环C ++期间的值错误

时间:2015-05-31 07:40:43

标签: c++ loops do-while

我在代码的do-while循环中遇到了一些麻烦。 它是关于一个接口类,它对用户输入的值进行验证。我正在使用Visual Studio 2012.

int Interface::requestOption(){
int option; //El problema está aquí
do{
    cout<<"--------------------------------"<<endl;
    cout<<"Type an option...";
    cin>>option;
    if(option<1 || option>8){
        cout<<"Invalid value, type again "<<endl;
        Sleep(2000);
        system("cls");
        menu();
    }
}while(!(option>0 && option<9));
return option;

}

如果我是第一次使用该方法,它将返回我实际输入的值。但是当我再次调用它时,我调试时,我注意到选项的值是-893453,而且,它不允许我键入另一个数字(cin&gt;&gt;选项不起作用)。

正在调用该方法以在下一个方法中进行交互:

void Control::studentsControl(){
int op;
do{
    system("cls");
    interEst->menu();
    op = interEst->requestOption();
    Lista<Students>* students= NULL;
    students = U->getStudents();
    switch(op){

    //Eight options
   //The 8th option is to return to the previous menu.

}while(op != 8);

}

2 个答案:

答案 0 :(得分:1)

每次迭代后调用std::cin.clear(),然后输入新值。

答案 1 :(得分:0)

对于!(option>0 && option<9) True

-893453!(False && True) == !False == True。为什么不在if语句中使用(option<1 || option>8)