C++ 输入错误的无限循环

C++ 输入错误的无限循环,c++,cin,C++,Cin,在下面的代码中,我希望循环,直到用户提供正确的输入。但当我尝试时,它正在变成一个不间断的循环。 请输入有效的输入。 没有while循环也是一样的 这里是while循环: #include <iostream> #include <fstream> #include <string> #include <ctime> #include <sstream> using namespace std; class library { publ

在下面的代码中,我希望循环,直到用户提供正确的输入。但当我尝试时,它正在变成一个不间断的循环。
请输入有效的输入。

没有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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
类库{
公众:
图书馆(){
int main选项;

问题是当你打电话的时候

cin>>mainOption; // mainOption is an int
但是用户没有输入
int
cin
会使输入缓冲区处于旧状态。除非您的代码使用输入的无效部分,否则最终用户输入的不正确值将保留在缓冲区中,导致无限重复

以下是如何解决此问题:

} 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
}
}其他{

coutPlease不要像正常情况那样使用构造函数functions@clcto你的意思是,当contractors有参数时,我们应该使用它?构造函数用于设置对象的初始状态。这一切都应该在
void run()
函数中。你甚至不需要对象来实现这一点。
} 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
}