Thread: Clearing unexpected values out of cin

  1. #1
    Registered User IdioticCreation's Avatar
    Join Date
    Nov 2006
    Location
    Lurking about
    Posts
    229

    Clearing unexpected values out of cin

    My program expects 3 numbers entered by the user. Currently if the user enters 4, or more numbers the program will still run, but the extra value will carry over later on. I would like to know if there is a standard way of clearing cin.

    Is this what cin.get() is for, I couldn't find a satisfying explanation.

    Thank you,
    David

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    The standard way to clear cin is
    Code:
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    You have to #include <limits> and <ios> for numeric_limits and streamsize. This should work well if you are using operator>> to read in your numbers, since it will not cause any issues on valid input either.

    Another option is to use getline to read into a string, then place the contents of that string into a stringstream and get the numbers out of there. Anything leftover in the stringstream will just not be processed. This has the added benefit of keeping cin from entering a fail state if the user enters bad data (like non-numeric characters), since getline accepts all characters. However, you can also just add similar code to handle that situation directly with cin.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 04-12-2009, 05:49 PM
  2. disposing error
    By dropper166 in forum C# Programming
    Replies: 2
    Last Post: 03-30-2009, 11:53 PM
  3. Replies: 2
    Last Post: 11-19-2008, 02:36 PM
  4. IRC-type logger with files based on three values
    By Lechx in forum C Programming
    Replies: 4
    Last Post: 08-27-2008, 04:42 PM
  5. cin not allowing input after first use of function
    By Peter5897 in forum C++ Programming
    Replies: 5
    Last Post: 01-31-2006, 06:29 PM