Thread: Infinate loop that shouldn't be.

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    4

    Infinate loop that shouldn't be.

    Hello I am new to C++ but am currently working as a C# programmer (whatever that means) and I am having a bit of trouble.

    I have been reading the beginners Tutorials of this site(Cprogramming.com) and I am up to lession 5, switch case, relativly simple, nothing really different so far, or so I thought.
    I have created a simple numbers program that request the user enter a number and then it tells the user if the number is higher, lower, or equal to 5(for no other reason then 5 is the first number that poped in my head). but somehow after entering the switch statement I have created an infinate loop that skips the user input statements. well to be more accuract it skips the cin >> veriable; statement because it prints the prompt to enter a number, when I enter say a letter instead of a number. e.g. if I enter a, it goes into the switch statement and prints the error message and then loops. personally I think that the program should just crash if I enter a letter instead of a number unless I do some sort of error trapping considering how I am storing a char in an int, so if someone could explain why that works too that would be nice.

    I am using Code;;Blocks 10.05 as my compiler

    and this is my code:

    Code:
     
    //libraries to be included
    #include <iostream> 
    
    using namespace std;
    
    //Function prototypes
    int DissplayNumber(int firstNumber);
    void GreaterThen();
    void EqualT0();
    void LessThen();
    
    int main()
    {
        int firstNumber = 1;  //Variable which holds the users input.
        while(firstNumber != 0) //The Main loop which runs the program until the user enters 0 to exit.
        {
         firstNumber = DissplayNumber(firstNumber);
        }
        return 0;
    }
    
    int DissplayNumber(int firstNumber)
    {
        cout << "Please enter a number, or enter 0 to exit:"; /* Propts the user to enter a Number */
        cin >> firstNumber; // reads the users input and stores it in firstNumber.
        cin.ignore(); //used to get ride of return keystroke, I guess that is useful.
    
        switch(firstNumber)
        {
            case 0:  //if the user enters 0 exit the program.
            cout << endl << "Good bye cruel world!";
            return firstNumber;
            break;
            case 5: //if the user enters 5 tell them they entered 5.
            EqualT0();
            break;
            default: // if the user enters anything but a number, display error and restart.
            cout << endl << "Error, bad input.";
            firstNumber = 1;
            return firstNumber;
            break;
        }
        if(firstNumber > 5) // if the number is greater then 5 call GreaterThen
        {
            GreaterThen(); 
        }
        else if(firstNumber < 5)// if the number is less then 5 call LessThen
    
        {
            LessThen();
        }
        cout << endl << "Your number is: " << firstNumber << endl;
        return firstNumber;
    }
    void GreaterThen()
    {
        cout << endl << "Your Number is Greater then 5.";
    }
    void EqualT0()
    {
        cout << endl << "Your Number is 5";
    }
    void LessThen()
    {
       cout << endl << "Your Number is Less then 5";
    }

    Again, thank you for taking the time, and if this has been explained somewhere else forgive me, and simply post a link to that location, and feel free to add the word noob a few times.

    -William

  2. #2
    Registered User
    Join Date
    Sep 2004
    Posts
    124
    A pogram should never crash because of invalid input; it should be handled with a message saying that the input is duff, and prompt for another one.

    I'm not a c++ or c# programmer, but as I see it your case statement will handle the specific cases of the digit zero being input and the digit 5. Everything else will go to the default. Is this the desired effect? I don't think so.

    The return statements in the switch block will cause the function DissplayNumber() to return, and as there is a return in all three cases, the code after the switch block will never execute.
    I think you can put a signature here.

  3. #3
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,246
    Read about cin.
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

  4. #4
    Registered User
    Join Date
    Mar 2010
    Posts
    109
    I'm not sure what you are complaining about. I guess just the fact that when you input a non-numerical value your program doesn't crash? I'm sure the streaming operator for cin sees that you are placing the stored value inside an int and is casting the value to an int. After all, all characters have a numerical equivalent and it's not uncommon to use that numerical value; e.g., seeing if a character falls between other characters.

  5. #5
    Registered User
    Join Date
    Jun 2010
    Posts
    4
    Thank you Driver for pointing out that fact that even if I enter a correct number that it will never get to my greater than or less than code.

    maybe I didn't explain my problem very well. when I enter a letter into the code. it no longer allows me to enter another number. it just keeps looping through the code printing "Please enter a number, or enter 0 to exit: Error, bad input"

    causing an infinate loop that I have to close the program to exit.

    why is it skipping over cin >> firstnumber when I enter an improper number.

    thanks,
    william

  6. #6
    Registered User
    Join Date
    Jun 2010
    Posts
    4
    here is my revised code to fix the error Driver pointed out.

    Code:
    //libraries to be included
    #include <iostream>
    
    using namespace std;
    
    //Function prototypes
    int DisplayNumber(int firstNumber);
    int NotEqualTo(int firstNumber);
    void GreaterThen();
    void EqualT0();
    void LessThen();
    
    int main()
    {
        int firstNumber = 1;  //Variable which holds the users input.
        while(firstNumber != 0) //The Main loop which runs the program until the user enters 0 to exit.
        {
         firstNumber = DisplayNumber(firstNumber);
        }
        return 0;
    }
    
    int DisplayNumber(int firstNumber)
    {
        cout << "Please enter a number, or enter 0 to exit:"; /* Propts the user to enter a Number */
        cin >> firstNumber; // reads the users input and stores it in firstNumber.
        cin.ignore(); //used to get ride of return keystroke, I guess that is useful.
    
        switch(firstNumber)
        {
            case 0:  //if the user enters 0 exit the program.
            cout << endl << "Good bye cruel world!";
            return firstNumber;
            break;
            case 5: //if the user enters 5 tell them they entered 5.
            EqualT0();
            break;
            default: // if the user enters anything else
            firstNumber = NotEqualTo(firstNumber);
            break;
        }
        cout << endl << "Your number is: " << firstNumber << endl;
        return firstNumber;
    }
    
    int NotEqualTo(int firstNumber)
    {
         if(firstNumber > 5) // if the number is greater then 5 call GreaterThen
         {
            GreaterThen();
         }
         else if(firstNumber < 5)// if the number is less then 5 call LessThen
         {
            LessThen();
         }
         else // if the user enters something other then a number display error and restart.
         {
            cout << endl << "Error, bad input.";
            firstNumber = 1;
         }
         return firstNumber;
    
    }
    
    void GreaterThen()
    {
        cout << endl << "Your Number is Greater then 5.";
    }
    void EqualT0()
    {
        cout << endl << "Your Number is 5";
    }
    void LessThen()
    {
       cout << endl << "Your Number is Less then 5";
    }
    Last edited by Blizard6; 06-15-2010 at 12:05 PM.

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> why is it skipping over cin >> firstnumber when I enter an improper number

    Because it expects a number, and if it doesn't get one, it sets the failbit for the stream. Until you clear that, all other attempts to read from cin will fail.

    There are several possible solutions if you want to validate the user input (i.e. handle it nicely when the user inputs something that isn't a number). None of them are both elegant and easy. My preferred suggestion is to put the input into a loop and loop until the user gives proper value. Adjust this example to suit your needs
    Code:
    int user_input = 0;
    while (!(cin >> user_input))
    {
        // clear the failbit
        cin.clear();
    
        // ignore all bad characters from stream
        // #include <limits> and <ios> (I think), or just use 1000 for the first argument
        // note that this will also ignore the return keystroke when the user enters data properly
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    
        // Error message and re-prompt
        cout << "Invalid input, try again: ";
    }
    
    // Input was successfully provided.
    If you have lots of these types of inputs, sometimes it is nicer to put that code into a function. Or you can search around to find functions that others already wrote and posted to do that type of thing.

  8. #8
    Registered User
    Join Date
    Jun 2010
    Posts
    4
    WoW... very nice, that works perfectly. thank you!

    so if it cin doesn't like what it gets it has to be cleared before it can be used again.

    thank you Daved

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 10:44 AM
  2. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  3. A somewhat bizzare problem!!! - WHILE LOOP
    By bobthebullet990 in forum C Programming
    Replies: 3
    Last Post: 03-31-2006, 07:19 AM
  4. Infinate Loop, not for all
    By Erf in forum C++ Programming
    Replies: 1
    Last Post: 07-22-2004, 02:26 AM
  5. when a while loop will stop ?
    By blue_gene in forum C Programming
    Replies: 13
    Last Post: 04-20-2004, 03:45 PM