Thread: Input validation loop failure

  1. #1
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Location
    CA, USA
    Posts
    466

    Input validation loop failure

    Code:
    double readDouble( void )
    {
        double input;
    
        while (!(cin >> input))
        {
            cout << "Invalid data.\n";
            cin.clear();
            cin.ignore(numeric_limits< double >::max(), '\n');
        }
        return input;
    }
    I get this warning when compiling on Dev-C++ 4.9.9.2

    Code:
    68 C:\Projects\CISP400\invdata.cpp [Warning] passing `double' for converting 1 of `std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::ignore(std::streamsize, typename _Traits::int_type) [with _CharT = char, _Traits = std::char_traits<char>]'
    Problem is that if I enter a character or any invalid data it goes into the infinite loop that I am trying to avoid. I have the same loop in a function for integers but no problems there.

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Look at the defintion of cin.ignore() and the types of its parameters. Then, look at the types you are passing it. In C++, the types of the arguments you send to a function have to match the types of the parameters in the function definition.

  3. #3
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Location
    CA, USA
    Posts
    466
    Ok, it takes an integer. I tried static_cast 'ing the whole expression to an int but still get infinite loop. Is there any way to do what I'm trying here?

  4. #4
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Try:

    cin.ignore(numeric_limits<streamsize >::max(), '\n');

  5. #5
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Location
    CA, USA
    Posts
    466
    Ah, very nice. Much appreciated.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can't get loop to work or validation
    By eminem3150 in forum C++ Programming
    Replies: 11
    Last Post: 01-15-2008, 06:21 AM
  2. Infinite Loop when entering invalid input
    By acwheat in forum C Programming
    Replies: 5
    Last Post: 04-18-2006, 04:17 PM
  3. bizarre anomaly in input loop with getche()
    By Dragaard in forum C++ Programming
    Replies: 2
    Last Post: 04-14-2006, 02:12 PM
  4. for loop not letting me input variable data
    By RealityFusion in forum C++ Programming
    Replies: 6
    Last Post: 09-21-2005, 04:29 PM
  5. input validation making sure only an int is entered
    By bazzano in forum C Programming
    Replies: 10
    Last Post: 09-06-2005, 06:14 AM