Thread: determine user's input

  1. #16
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    If a is an int, then cin>>a will read in characters from input until it can no longer use the characters to form a valid integer. In this case, it reads in 2 but stops at the '.' because you can't have a decimal point in an integer.

    If you want a number that contains decimals, change a to be a double instead of an int. If you want your program to fail when it asks for an int but the user types a number with a decimal, you'll have to add another tweak:
    Code:
    if ((cin >> a) && (cin.get() == '\n'))
    That code reads into a, and then checks to see if there are any other characters after the integer. If the user types 2.45, then the cin.get() will get the decimal point, which isn't '\n'. If the user types in 68sdf8a6s, then it will read 68 into a and then fail because 's' is not '\n'. If they do it correctly and type 239, then cin.get() will get the newline from when they hit <enter>, and the read will succeed.
    Last edited by Daved; 05-11-2009 at 10:14 AM.

  2. #17
    Registered User
    Join Date
    May 2009
    Posts
    3
    thank you so much sir it works...

  3. #18
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Daved View Post
    If they do it correctly and type 239, then cin.get() will get the newline from when they hit <enter>, and the read will succeed.
    What if they type 239 followed by a space?
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  4. #19
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Then the program will sit there waiting for them to hit <enter>, since input from the console isn't available to the program until <enter> is hit. At that point, the input would be rejected because "239 " is not a number.

    Obviously it's not perfect, but for most of these beginner programs it's more than enough.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Input statement problem
    By une in forum C Programming
    Replies: 3
    Last Post: 05-29-2007, 11:16 PM
  2. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  3. reading data from the users input
    By SpEkTrE in forum C++ Programming
    Replies: 1
    Last Post: 04-10-2005, 06:15 PM
  4. Custom Made Safe Input Function
    By Beast() in forum C Programming
    Replies: 6
    Last Post: 08-21-2004, 10:19 PM
  5. need help with some input
    By blindleaf in forum C Programming
    Replies: 2
    Last Post: 03-16-2003, 01:50 PM