Entering valid user input?

This is a discussion on Entering valid user input? within the C++ Programming forums, part of the General Programming Boards category; Hello guys; I am wondering if you can help me. How can I write my simple program so if the ...

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    6

    Entering valid user input?

    Hello guys; I am wondering if you can help me.
    How can I write my simple program so if the user enters an invalid number,
    The program won’t exit? I know I am supposed to use a if (cin) or if (!cin),
    But I don’t know where in the program or how I should use it. Right now my
    Program looks kind of like this:
    If (number > 1 && number < 1001)
    Go through some function loops
    Else
    Cout << “invalid number”;
    I need to write it so when the user enters an invalid number, the program
    Would Keep asking for the right number until it's given.
    Thanks guys.
    Last edited by Frank1234; 03-19-2013 at 07:54 PM.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,451
    Like so.
    Code:
    #include <iostream>
    #include <iomanip>
    #include <limits>
    using namespace std;
    
    int main()
    {
      int var = 0;
      do {
        if ( cin >> var ) {
          if ( var >= 1 && var <= 99 ) {
            cout << "Good" << endl;
          } else if ( var != -1 ) {
            cout << "Out of range" << endl;
          }
        } else {
          cout << "Garbage input" << endl;
          cin.clear();
          cin.ignore(numeric_limits<streamsize>::max(),'\n');
        }
      } while ( var != -1 );
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Error when login with valid user!!!
    By Gil Carvalho in forum C Programming
    Replies: 3
    Last Post: 06-20-2012, 02:48 PM
  2. Entering a user equation to a source function ?
    By dcuneo in forum C++ Programming
    Replies: 5
    Last Post: 03-01-2008, 04:38 AM
  3. preventing user entering characters
    By Ashkan in forum C Programming
    Replies: 12
    Last Post: 08-24-2003, 12:56 PM
  4. User Entering Numbers
    By ct26torr in forum C Programming
    Replies: 1
    Last Post: 01-26-2003, 12:40 PM
  5. User entering I/O File names at command line
    By Wiggin in forum C++ Programming
    Replies: 6
    Last Post: 04-27-2002, 12:43 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21