0

I need to validate the user input through cin my code is as below :

#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;

}

3
  • 1
    This might help: parashift.com/c++-faq/istream-and-ignore.html Commented Jan 13, 2013 at 14:27
  • 1
    You haven’t really explained what the problem is (but see chris’ comment). Also, while (1) => while (true) and I’d replace exit(1) by return 1. Commented Jan 13, 2013 at 14:29
  • @KonradRudolph yeah that i can do and chris comment i checked i think that will resolve my problem....i need just a user input from 0 to 2 and reject other inputs and to angin ask from user for the input. Commented Jan 13, 2013 at 14:31

1 Answer 1

1

A simple sample:

#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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.