Thread: stream - discard the valid input

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    30

    stream - discard the valid input

    Hi all,

    i was trying to type the same program from a book that does the following:
    Program requests to enter a number 0 -100.
    The program checks if the entry is valid, if not, the faildbit should be cleared (cin.clear) and invalid entry discarded (cin.ignore).

    if itry this code and enter a text instead of a number, i run into an endledd loop of "Invalid number. Try again"

    Code:
        while (true) {
            cout << "Enter a number between 0 - 100" << endl;
            cin >> d;
    
    
            if (!cin.good()) {
                cout << "Invalid input. Try again" << endl;
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                cin.clear();
                continue;
            }
            if (d < 0 || d > 100) {
                cout << "Wrong range. Try again" << endl;
            }
            else {
                cout << "You entered " << d << endl;
                break;
            }
        }
        return 0;
    checking the book again, i saw i switched 2 lines. i should ignore than clear

    Code:
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin.clear();
    i dont' unterstand how the order of those 2 lines, is having this impact? it seems for me also correct, to discard first and clear the failbits.

    i wouls be gratefull for any hints

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    The order matters. If the stream enters a fail state no further processing of that stream can occur until the errors are cleared. This means that the clear() must be the first thing done.

  3. #3
    Registered User
    Join Date
    Nov 2018
    Posts
    30
    That makes a lot of sense, thanks a lot, a very useful info

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Entering valid user input?
    By Frank1234 in forum C++ Programming
    Replies: 1
    Last Post: 03-19-2013, 11:42 PM
  2. Validating valid input?
    By audifanatic518 in forum C++ Programming
    Replies: 3
    Last Post: 04-30-2012, 01:04 AM
  3. Discard wrong data from stream
    By mesmer in forum C Programming
    Replies: 7
    Last Post: 11-16-2008, 02:30 AM
  4. Help loading a vector with input from input stream
    By Bnchs in forum C++ Programming
    Replies: 9
    Last Post: 11-07-2006, 03:53 PM
  5. How do you check for valid input?
    By Elite in forum C Programming
    Replies: 14
    Last Post: 03-08-2005, 03:16 PM

Tags for this Thread