Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

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

  • 05-10-2008 11:46AM
    #1
    Closed Accounts Posts: 27,856 ✭✭✭✭


    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, Registered Users 2 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,093 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,856 ✭✭✭✭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