can't display int value

Hi All

Please help me with the following code, it works fine when i enter
1234567890 but goes mad when i enter one more digit i.e 12345678901.
It keeps on looping and displays infinitely:-

"Invalid Input. Please try again.!!"

How can i fix/correct this?

Any help will be appreciated!

***********************************************************
#include <iostream>
#include <cassert>
using namespace std;

int main( )
{
int aDigit[ 5 ];

cout << "Enter 5 digits, each on a new line." << endl;

cout << "Your digits must be between 0 and 9: " << endl;

for ( int i = 0; i < 5; )
{
cin >> aDigit[ i ];

if((aDigit[i] >= 0) && (aDigit[i] <= 9))
{
cout << "Thank you. That is accepted as number " << i+1 <<"." << endl;
i++;
}
else
{
cout << "Invalid Input. Please try again.!!" << endl;

}

}

cout << endl << "Digits in reverse order:" << endl;

for ( int j = 4; j >= 0; j-- )
{
cout << aDigit[ j ] << endl;
}

return 0;
}
************************************************************


Perhaps 12345678901 is larger than an int can hold? I'm not exactly sure about that being a problem but...
yep, 12345678901is too big for an integer.
i'm not sure why it's going havoc with cin, but you can try this workaround.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cmath>

using namespace std;

int main( ) {
   int aDigit[ 5 ];
   cout << "Enter 5 digits, each on a new line." << endl;
   cout << "Your digits must be between 0 and 9: " << endl;

   double input;
   for ( int i = 0; i < 5; ) {
      cin >> input;

      if (input <= pow(2.0 , 8*(double)sizeof(int))-1) {
         aDigit[i] = (int) input;

         if((aDigit[i] >= 0) && (aDigit[i] <= 9)) {
            cout << "Thank you. That is accepted as number " << i+1 <<"." << endl;
            i++;
         } else {
            cout << "Invalid Input. Please try again.!!" << endl;
         }
      } else {
         cout << "Invalid Input. Out of Range!!!" << endl;
      }
   }
   cout << endl << "Digits in reverse order:" << endl;

   for ( int j = 4; j >= 0; j-- ) cout << aDigit[ j ];
   cout << endl;

   return 0;
}
Last edited on
oh, i forgot something.
maybe you want to test that your input is also positiv you have to change line 15 to
 
if ((input >=0) && (input <= pow(2.0 , 8*(double)sizeof(int))-1)) {
or insert in your code after
 
cin >> aDigit[i];

the code snippet
1
2
3
4
if (cin.fail()) {
   cin.clear();
   aDigit[i]=11;
}

that should also do the trick.
IMO. I would use

1
2
string input;
getline(cin, input);


instead of cin >> input;.

Then you can check once you have the input if it's a valid number.
Topic archived. No new replies allowed.