Thread: ensure input is only integer

  1. #1
    Registered User
    Join Date
    Feb 2006

    ensure input is only integer

    Good day, I was writing a program in C++.I was validating to ensure that only integer is accepted.

    that is for int a;
    a can take the value of single digit or double digit numbers like (13/123213/2312321).

    Is there any way to check,that FOR variable a,
    ONLY digits are entered and
    NO decimal(like 2.4 1.002) or characted has been inputed?

  2. #2
    Join Date
    Jan 2006
    I'd say you want to grab your input with getine(), which will effectively put the number into a string. Using that you can check for decimals, and then use a stringstream to convert the string back into a number.

    If the stringstream conversion fails, what the user entered was probably not a number.

  3. #3
    Registered User Noir's Avatar
    Join Date
    Mar 2007
    Why not just use cin and check if it failed to read an int?
    int a;
    if ( cin >> a ) {
      // it read an int
    } else {
      // not an int
    You can put all of that in a loop:
    cout << "enter an integer> ";
    while ( !( cin >> a ) ) {
      cin.ignore( 256, '\n' );
      cout << "not an integer; try again> ";

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Does numeric overflow count as a 'problem' as well for your input ?
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fscanf %s or %d integer input space char stop question...
    By transgalactic2 in forum C Programming
    Replies: 5
    Last Post: 04-14-2009, 10:44 AM
  2. Input class project (again)
    By Elysia in forum C++ Programming
    Replies: 41
    Last Post: 02-13-2009, 10:52 AM
  3. Reading Input from file (Integer array)
    By Govalant in forum C Programming
    Replies: 9
    Last Post: 07-23-2007, 06:13 PM
  4. Reading the input file into integer arrays
    By supaben34 in forum C++ Programming
    Replies: 3
    Last Post: 12-06-2002, 07:04 PM
  5. Reading input as an integer
    By n0de in forum C++ Programming
    Replies: 4
    Last Post: 04-11-2002, 06:52 PM