Thread: Data types and user input

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    1

    Data types and user input

    Greetings. I have recently started learning C++ and I do have some knowledge as far as C goes. Anyway I've written some simple programs and one problem I constantly run into is validating the users input. For an example I will prompt the user to enter an integer, but if the user inputs a character the program goes berserk. Is there anyway to ensure the user inputs the correct data type? Thank you in advance.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    One way is to read the input as a string then parse the input, e.g., using a string stream. Another way is to check that the input read succeeded. If not, clear the error state of the input stream, then discard the input left in the input buffer and read again.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    The Negativity. LAURENT*'s Avatar
    Join Date
    May 2012
    Posts
    68
    I think you use cin.("ignore"). I'm not very good but I suggest you read for characters too and make up a response for them. Maybe a loop statement might help.

  4. #4
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    This from C,not from C++ isalpha - C++ Reference

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. data types types...
    By gftmc in forum C++ Programming
    Replies: 3
    Last Post: 09-11-2006, 11:30 AM
  2. Stl lists and user defined types
    By figa in forum C++ Programming
    Replies: 8
    Last Post: 03-28-2005, 12:09 PM
  3. reading input files with different types of data
    By sanu in forum C++ Programming
    Replies: 4
    Last Post: 06-27-2002, 08:15 AM
  4. Replies: 6
    Last Post: 04-12-2002, 08:33 AM
  5. external user defined types
    By doubleanti in forum C++ Programming
    Replies: 6
    Last Post: 12-16-2001, 04:07 PM