C++ 用户输入验证使用";cin";

C++ 用户输入验证使用";cin";,c++,visual-c++,cin,C++,Visual C++,Cin,我需要通过cin验证用户输入,我的代码如下: #include"iostream" using namespace std; int main() { int choice = 0; while(1) { cout<<"ENTER your choice a value between 0 to 2"<<endl; cin>>choice; // Here i need some logic which w

我需要通过cin验证用户输入,我的代码如下:

#include"iostream"
using namespace std;

int main()
{
int choice = 0; 
while(1)
{
    cout<<"ENTER your choice a value between 0 to 2"<<endl;
        cin>>choice;    

        // Here i need some logic which will work like "choice" can be only
        // Integer and within the range i.e. 0 to 2 and if it is not
    // satisfy condition then ask user to input again
    switch(choice)
    {
    case 0:
        exit(1);
        break;

    case 1:
       fun();
       break;
    case 2:
       fun1();
       break;
    default: cout<<"Please enter a valid value"<<endl;
            break;
    }
}

return 0;
#包括“iostream”
使用名称空间std;
int main()
{
int-choice=0;
而(1)
{
一个简单的样本:

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

template <typename T>
bool toNumber(const std::string &x, T &num)
{
    return (std::stringstream(x) >> num);
}
int main() {
    while (true) {
        cout << "ENTER your choice a value between 0 to 2" << endl;

        string s;
        cin >> s;

        int choice = 0;

        if (toNumber(s, choice)) {
            switch (choice) {
              case 0: exit(1); break;
              case 1: fun();   break;
              case 2: fun1();  break;
            }
        }
        else
            cout << "Please enter a valid value" << endl;
    }
}
#包括
#包括
#包括
使用名称空间std;
模板
bool toNumber(常量std::string&x,T&num)
{
返回(std::stringstream(x)>>num);
}
int main(){
while(true){
库特;
int-choice=0;
如果(吨数,选择)){
开关(选择){
案例0:退出(1);中断;
案例1:乐趣;休息;
案例2:fun1();中断;
}
}
其他的

这可能会有帮助:您还没有真正解释问题所在(但请参见chris的评论)。另外,
while(1)
=>
while(true)
,我将替换
退出(1)
by
return 1
@KonradRudolph是的,我可以做,我检查了chris comment,我认为这将解决我的问题……我只需要一个从0到2的用户输入,拒绝其他输入,并向angin请求用户输入。