cin expecting number but gets a letter

This is a discussion on cin expecting number but gets a letter within the C++ Programming forums, part of the General Programming Boards category; i'm using a simple switch statement to get user input. from 1 to 5. what if they enter 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,672
    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
    I used to be an adventurer like you... then I took an arrow to the knee.

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, 09:12 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21