# keeping number small fails

## Recommended Posts

I'm trying to limit the size of the number the user can input, by comparing it to the max (50000).
#include <iostream>
using namespace std;

int a;
int main()
{
cin >> a;
if (a>50000)
{
cout<< "Input a lower number";
cin >> a;
}
cout<<"My number is "<< a <<endl;
}

However, if the user inputs some very large number, the program says: My number is 0. What can I do?

##### Share on other sites
don't use an int. use a long. That'll give you a bigger range for you to put in big numbers.

##### Share on other sites
Use cin.getline instead and let the user enter any string he wants. Then you can do sanity checks on it. Also, your code there won't work out too well if the user enters a big number the second time.

##### Share on other sites
Thanks for the tip but the idea is how to TOTALLY prevent the possibility of the user inputting an extremely large number, larger than long!

##### Share on other sites
The likely problem is that you're entering a number so large that the parser can't fit it in an int. You need to check to see if the input succeeded, and if not, do some error handling in addition to checking the value. Ex:
int main(){    int a;    for (;;) {      std::cin >> a;      if (!std::cin) {        std::cout << "Error parsing input. Enter a new number.\n";        std::cin.ignore(std::cin.rdbuf()->in_avail());        std::cin.clear();      } else if (a > 50000) {        std::cout << "Number is too large. Enter a new number.\n";      } else break;    }    std::cout<<"My number is "<< a <<endl;}

##### Share on other sites
Grab the characters of the number one at a time then do some simple math to compute a final value. That or you could use iostream's read function http://www.cplusplus.com/reference/iostream/istream/read.html

##### Share on other sites
Thanks SiCrane, but could you tell me how to do this in a Win32 project, not a console one?

##### Share on other sites
You could read the input into a string, and then go through it looking for queues of integers.

If you don't care that much you could use a unsigned long long, i doubt someones gonna enter a number that cannot be stored in an unsigned long long.

##### Share on other sites
Quote:
 Original post by asdqweThanks SiCrane, but could you tell me how to do this in a Win32 project, not a console one?
How are you reading the number in in your Win32 project? Where is the input coming from? If it's as a string (or char* buffer), you can use std::stringstream to parse it as SiCrane suggested.

Quote:
 Original post by MadsGustafIf you don't care that much you could use a unsigned long long, i doubt someones gonna enter a number that cannot be stored in an unsigned long long.
You mean a number bigger than 18446744073709551616? That's not that big if you hold down '9' for a second or two.