Data types and user input

This is a discussion on Data types and user input within the C++ Programming forums, part of the General Programming Boards category; Greetings. I have recently started learning C++ and I do have some knowledge as far as C goes. Anyway I've ...

  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
    21,589
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User LAURENT*'s Avatar
    Join Date
    May 2012
    Posts
    32
    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,675
    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, 11:09 AM
  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, 03:07 PM

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