Thread: cin expecting number but gets a letter

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    33

    Smile cin expecting number but gets a letter

    i'm using a simple switch statement to get user input. from 1 to 5.

    what if they enter a letter, whilst my cin is expecting an int. is there a way to catch that before it causes problems with my program?
    werdy666!

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Test the input stream after the attempt is made to read the number. If the stream is in an error state, then something happened and you should clear the error state, dump the contents of the stream and ask the user for more (and hopefully valid) input.

    Code:
    #include <limits>
    
    ...
    
    int value;
    cout << "Enter an int: ";
    while( !(cin >> value) )
    {
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "I said enter an int you idiot: ";
    }
    
    ...
    
    // continue on with rest of code
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 10:13 AM
  2. counting letter occurences in a string
    By pjr5043 in forum C++ Programming
    Replies: 35
    Last Post: 05-05-2008, 09:18 PM
  3. Issue w/ Guess My Number Program
    By mkylman in forum C++ Programming
    Replies: 5
    Last Post: 08-23-2007, 01:31 AM
  4. Perfect number...
    By Argo_Jeude in forum C++ Programming
    Replies: 8
    Last Post: 07-12-2005, 01:53 PM
  5. Replies: 1
    Last Post: 03-06-2005, 10:12 AM