使用“cin”进行用户输入验证

时间:2013-01-13 14:26:18

标签: 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 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;

}

1 个答案:

答案 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;
    }
}