Dxccr
Dxccr

Reputation: 13

How to limit cin to integers within the int data range?

I am wondering how to only allow inputs for a cin which are within the int data range.

// This program counts the number of digits in an integer
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int i, k;
    cout << setw(20) << "Value Entered" << setw(20) << "Number of Digits" << endl;
    while(1==1)
    {
        k = 1;
        cout << setw(10) << "";
        cin >> i;
        while(i > 2147483647 || i < -2147483648)
        {
        cout << setw(10) << "";
        cin >> i;            
        }
        while( i / 10 > 0)
        {
            i = i / 10;
            k++;
        }
        cout << setw(30) << k << endl;
    }

    return 0;
}

With the method I have it just gets stuck in the loop repeating 1.

EDIT:

Sample Output Format (Required)

    "Value Entered"   "Number of Digits"
          14                  2
         225                  3
       -1000                  4

Sample Output (What I have)

       Value Entered    Number of Digits
          45
                             2
          456
                             3
          258
                             3
          -2546
                             4

Upvotes: 0

Views: 274

Answers (1)

David G
David G

Reputation: 96810

The extraction will fail if the number falls outside of the range for the type that it's being read into. When this happens the state of the stream will be set to failure, so you simply need to check for this state, and then reset the stream to a valid state:

while (!(cin >> i)) {
  cin.clear();
  cin.ignore(numeric_limit<streamsize>::max(), '\n');
}

clear() clears the error flags and ignore() puts the stream on a new line so that new data can be read. You may need to include <limits> for the code to work.

The condition for your second loop should be while (i > 0). As you had it you were off by one digit.

Upvotes: 1

Related Questions