Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

C++: Validate input: Ensure input is int?

Options
  • 05-10-2008 11:46am
    #1
    Closed Accounts Posts: 27,857 ✭✭✭✭


    Hey folks,

    I'm doing a little project at the moment and I'm trying to figure out what's the best method to validate the input.

    The program prompts the user for an int (for a few functions actually), and I want to ensure that an int -- and only an int -- is accepted.

    I've been browsing around looking for ideas, and this is my current attempt:
    int number, m;
    bool o;
    	do {
    		cout << "Please enter an integer:";
    		cin >> m;
    		if(cin >> m && isdigit(m)) {
    			number = m;
    			o = 1;
    			break;
    		} else {
    			o = 0;
    		}
    	} while(o == 0);
    

    But it keeps looping through and printing 'please enter.....' if I enter a non-int.

    Any ideas? All the methods I've seen are a bit messy, so anything a bit neater would be great!

    ps. 3rd year comp sci student, but 1st year doing C++, so go easy!


Comments

  • Registered Users Posts: 901 ✭✭✭EL_Loco


    try putting a cout statement in each section of the IF and ELSE
    and see if it's triggering them correctly based on your input.

    sorry I can't be of specific C++ assistance :) it's been too long.


  • Moderators, Science, Health & Environment Moderators Posts: 10,079 Mod ✭✭✭✭marco_polo


    Just scanned the code but it looks to me to be the expected behaviour of the code as written, unless I'm missing something.

    If you enter a non-int then isdigit(m) will evaluate to false as a result the whole if clause will evaluate to false, o will be assigned to zero in the else section, and the do while loop will execute again as long as o is 0.


  • Closed Accounts Posts: 27,857 ✭✭✭✭Dave!


    Cheers lads

    I actually found an acceptable solution :)
    	int i = 0;
    	cout << "Enter int: ";
    	while (!(cin >> i)) {
    		cin.clear();
    		cin.ignore(1000,'\n');
    		cout << "Enter an integer value, dipsh*t!";
    	}
    		other_int = i;
    

    Finally finished this bloody thing I think!!!


Advertisement