错误输入的std :: cin无限循环

时间:2014-04-18 21:50:28

标签: c++ cin

在我的下面的代码中,我想循环,直到用户提供正确的输入。但是当我尝试它变成一个不间断的循环时 Please Enter Valid Input.
没有while循环,它也是一样的。

这里有while循环:

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <sstream>
using namespace std;

class library {
public:
    library() {
        int mainOption;

        cout<<"Please choose the option you want to perform."<<endl;
        cout<<"1. Member Section"<<"\n"<<"2. Books, Lending & Donate Section"<<"\n"<<"3. Returning Section"<<endl;
        bool option=true;
        while (option==true) {
            cin>>mainOption;
            if (mainOption==1) {
                cout<<"section 1"<<endl;
                option=false;
            } else if (mainOption==2) {
                cout<<"section 1"<<endl;
                option=false;
            } else if (mainOption==3) {
                cout<<"section 1"<<endl;
                option=false;
            } else {
                cout<<"Please Enter Valid Input. "<<endl;
                //option still true. so it should ask user input again right?
            }
        }
    }
};

int main(int argc, const char * argv[])
{
    library l1;
    return 0;
}

这里没有while循环。但同样的事情正在发生。

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <sstream>
using namespace std;

class library {
public:
    library() {
        int mainOption;

        cout<<"Please choose the option you want to perform."<<endl;
        cout<<"1. Member Section"<<"\n"<<"2. Books, Lending & Donate Section"<<"\n"<<"3. Returning Section"<<endl;

        cin>>mainOption;
        if (mainOption==1) {
            cout<<"section 1"<<endl;
        } else if (mainOption==2) {
            cout<<"section 1"<<endl;
        } else if (mainOption==3) {
            cout<<"section 1"<<endl;
        } else {
            cout<<"Please Enter Valid Input. "<<endl;
            library();//Calling library function again to input again.
        }
    }
};

int main(int argc, const char * argv[])
{
    library l1;
    return 0;
}

1 个答案:

答案 0 :(得分:4)

问题在于你打电话

cin>>mainOption; // mainOption is an int

但是用户输入intcin将输入缓冲区保留为旧状态。除非您的代码消耗输入的无效部分,否则最终用户输入的错误值将保留在缓冲区中,从而导致无限重复。

以下是解决此问题的方法:

} else {
    cout<<"Please Enter Valid Input. "<<endl;
    cin.clear(); // Clear the error state
    string discard;
    getline(cin, discard); // Read and discard the next line
    // option remains true, so the loop continues
}

请注意,我还删除了递归,因为您的while循环足以处理手头的任务。