Thread: Handling input from cin

  1. #1
    Registered User
    Join Date
    Aug 2001

    Question Handling input from cin

    My current project requires me to trap non-valid input (values that are not rational numbers) and return an error. The code I'm using is:
    // Input the value
    while (
    	cout << "Invalid value. Please enter a real number: ";
    	cin.ignore(1000, '\n'); // clean buffer
    	cin >> values[element]; // Ask for proper input
    However, my instructor's code is this:
    // Input the value
    char chrResponse;
    if (cin.rdstate() != 0)
    	cin >> chrResponse; // clean buffer
    // Ask for proper input
    Would both be correct, and which would be better?

  2. #2
    Registered User Strider's Avatar
    Join Date
    Aug 2001
    As long as your object "value" is type float or double (real number) and you input the value prior to your while loop, your code will work (not sure why you have an array?). Your professor's code, however, will not. The code uses type char. The char will allow you to input anything and just drop everything beyond 1 character. You would be hard pressed to get this to fail. Even if this would work, the code only clears the failbit and not the buffer. I believe what the instructor was basically trying to do, is test for the fail bit using a different method:
    // should use while condition instead of if in case
    // of bad input more than once
    while(cin.rdstate() == ios::failbit)
    // basically the same as
    while ( // looks for the bad or failbit
    Basically, your code works and your instrutor's code does not. Unless there is more to it that was not shown.

    One Ring to rule them all, One Ring to find them,
    One Ring to bring them all and in the darkness bind them
    In the Land of Mordor where the Shadows lie.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Input class project (again)
    By Elysia in forum C++ Programming
    Replies: 41
    Last Post: 02-13-2009, 10:52 AM
  2. Simple Console Input for Beginners
    By jlou in forum C++ Programming
    Replies: 0
    Last Post: 06-21-2005, 01:50 PM
  3. Problem with cin. Please help me.
    By Antigloss in forum C++ Programming
    Replies: 17
    Last Post: 06-06-2005, 09:50 AM
  4. Other than cin, how can a get a program to take input?
    By deathstryke in forum C++ Programming
    Replies: 15
    Last Post: 01-30-2003, 02:56 PM
  5. input from the user/exception handling
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 11-26-2001, 09:38 AM