Originally posted by: ghidu
how to validate that an integer doesn't have more than 10 digits in C++? I don't want to use arrays. thanks
Originally posted by: mugs
how about:
if(num <= 9999999999)
Originally posted by: xtknight
What you are seeing is the positive bounds of a 32-bit signed integer (((2^32)/2)-1) = 2147483647. You need to use a 64-bit to store the biggest 10 digit number. Declare it like so (i being the variable). In your current code, it may be overflowing the buffer (bad!)
Either signed or unsigned 64-bit will store the biggest 10 digit number. Unsigned 32-bit still only stores from 0 to 4294967295.
Signed 64-bit: -9223372036854775807 to 9223372036854775806
Unsigned 64-bit: 0 to 18446744073709551615
signed __int64 i;
//or this will work too I think. int64 makes sure it's 64-bit though because it could vary per compiler or architecture.
signed long i;
How are you going to deal with negatives? Does the minus count as a digit?
Originally posted by: xtknight
OK...this should work.
__int64 i;
//now get the number in i
if (i<=9999999999) {
//operation
}
Doesn't matter if you use signed or unsigned for a 10-digit positive number. The 64-bit integer has nothing to do with a 64-bit CPU. It should work on anything as far as I know. It's only the default size of an integer that can potentially vary. __int64 forces a 64-bit integer.
Actually instead you may want to do it by strings in case the number overflows the integer.
char* number = std::cin.getline();
//check with strlen
Something like that?? You should probably use string with C++ though. Not sure how to use the string type. This will probably work. Somebody correct me here.
Originally posted by: ghidu
d=cin.get();
while(d!='\n'||count<=10)
{
num=num*10+d;
count++;
d=cin.get;
}
Originally posted by: xtknight
Wait, there is a problem with your code...
What if count is greater than 10? Say count is 15. It'll only process the first 10 digits unless I'm out of my mind (possible) ? It has no way of knowing whether it was 10 digits or whether it was more than 10 digits. Try the getline() and length() way.