#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;
}
keeping number small fails
I'm trying to limit the size of the number the user can input, by comparing it to the max (50000).However, if the user inputs some very large number, the program says: My number is 0.
What can I do?
don't use an int. use a long. That'll give you a bigger range for you to put in big numbers.
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.
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!
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;}
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
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.
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.
Quote:Original post by asdqweHow 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.
Thanks SiCrane, but could you tell me how to do this in a Win32 project, not a console one?
Quote:Original post by MadsGustafYou mean a number bigger than 18446744073709551616? That's not that big if you hold down '9' for a second or two.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement