Thread: problem with do loop and if statement

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    1

    problem with do loop and if statement

    I'm trying to get a number of rooms and it can't be less than 1. I have this do loop with and if statement but when i enter invalid input it just outputs invalid output and goes onto my next function.

    Code:
    int num_of_rooms()
    {
    	int num_rm, valid = 1;
        
    	do
    	{
    	cout << "Enter the number of rooms: ";
    	cin >> num_rm;
    
    	if (num_rm < 1)
    		{
    		valid = 0;
    		cout << "Invalid input\n";
    		}
    	}while(valid = 0);
    
    	return num_rm;
    }

  2. #2
    Registered User
    Join Date
    Nov 2007
    Posts
    12
    Might be that 'while (valid = 0)' should have 2 ='s ('while (valid == 0)'). Also just so you know, if the first time you input less than one, it will never break from the loop because 'valid' will never change.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Also, since you're using valid like a boolean, you may as well make it a bool.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > while(valid = 0)
    This makes it false, even if it's still true!

    Compare, don't assign.

    Making it a bool variable would help, then you can just say
    while ( !valid )
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Salem View Post
    Making it a bool variable would help, then you can just say
    while ( !valid )
    Even if it's not bool, the expression (!valid) evaluates correctly for checking if the value is zero (or NULL for that matter). Otherwise backwards compatibility with C would be broken.

    I agree that the variable should be bool, since the "valid" variable only holds two possible values: true or false. This helps indicating the correct use of the variable. [It makes sure no-one thinks it's "the number of valid entries" or some such].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed