Thread: troubleshooting user's input mistakes

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    7

    troubleshooting user's input mistakes

    ok, so I am back here struggling with beginner's stuff.

    this is the question: when I prompt the user for some input, e.g.:

    int number;
    cin >> number;

    what can i do for trapping input errors, for example the user inputting a type of data which is different from the variable the program is waiting for? (some chars instead of an integer value or the like)
    thanks in advance

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    There are two ways of doing this.
    1) look into cin.good(),cin.fail(),cin.clear()
    2) get all input as a string using cin.getline and parse the string.If you need to covert to numbers there is atoi() and atof() to do that.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145

    or

    ...or make your own input-function. Perhaps you want to prevent the user from typing in more than say 10 letters. I don't think you can do that with cin/scanf.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. Troubleshooting Input Function
    By SiliconHobo in forum C Programming
    Replies: 14
    Last Post: 12-05-2007, 07:18 AM
  3. Input statement problem
    By une in forum C Programming
    Replies: 3
    Last Post: 05-29-2007, 11:16 PM
  4. limiting length of users input
    By Unregistered in forum C Programming
    Replies: 5
    Last Post: 11-20-2001, 09:55 AM