Thread: Switch problem

  1. #1
    Registered User
    Join Date
    Mar 2009

    Switch problem

    Hi all

    Surprised I haven't been able to find a solution to this when it must be a common problem...

    I am having trouble with a switch statement that is nested in a forever loop. The user is to input an unsigned short to determine which case the program should jump to. My problem is that if the user inputs a letter instead of a number, the program then keeps looping forever rather than simply going to the default case. Can anyone tell me how to fix this?

    Many thanks :-)


  2. #2
    The larch
    Join Date
    May 2006
    You'll need to check the state of the input stream:

    unsigned i;
    while (!(cin >> i)) {
        cin.clear(); //clear error status
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard any unread characters
    //now i contains input
    You might also check if the input error was eof, and break from the infinite loop in this case: may-be the user really wants to stop.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Switch statement problem
    By jalex39 in forum C Programming
    Replies: 6
    Last Post: 03-08-2008, 04:05 PM
  2. problem on switch
    By toxicherry in forum C Programming
    Replies: 11
    Last Post: 12-31-2007, 05:17 AM
  3. Switch Problem
    By Tynnhammar in forum C++ Programming
    Replies: 2
    Last Post: 09-16-2004, 11:57 AM
  4. Replies: 1
    Last Post: 08-31-2004, 04:07 AM
  5. Uh-oh! I am having a major switch problem!
    By goodn in forum C Programming
    Replies: 4
    Last Post: 11-01-2001, 04:49 PM