Click here to Skip to main content
15,894,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Okay, so I am making a C++ file handling project. There's this variable in it: int roll.
It should have 3 digits. I thought of using methods like, if(roll>99||roll<1000) but it's not useful. It takes 091 as a 2 digit number, 003 as 1-digit, obviously. So, How do I check if the input is a 3-digit number for an integer variable 'a', if I want to consider numbers like '001' as 3 digit numbers too?

What I have tried:

I thought of using methods like, if(roll>99||roll<1000) but it's not useful. It takes 091 as a 2 digit number, 003 as 1-digit, obviously.
Posted
Updated 2-Feb-18 3:54am
Comments
PeejayAdams 2-Feb-18 9:47am    
Would 52 be valid or would it need to be entered as 052? If both are valid, then you're simply looking at any number under 1000. If it has to be 052, then really you're looking for a string rather than an int, a regular expression ([0-9][0-9][0-9]) would be the way to go.
Leo Chapiro 2-Feb-18 9:48am    
Your question is not clear: an integer cann't looks like "001" but only like "1", the "001" is a string. You can convert it to integer: "001" -> 1. Is that what you need?
Richard Deeming 2-Feb-18 9:48am    
So what's wrong with if (roll > 0 && roll < 1000) ?
CPallini 2-Feb-18 11:20am    
Indeed. :-)
I would use
if ( roll >= 0 && roll < 1000)

It depends: if you are reading a value from a file, then you would need to do the if test you show, pretty much.
If you are generating a random number (and the name roll implies you are) then generate a random number between 0 and 899 inclusive, then add 100 to it. That way, you are guaranteed a value with a non-zero most significant digit.

Without the relevant code fragments, that's all we can say - there are too many different things you could be doing!
 
Share this answer
 
If it is an integer variable, checking for < 1000 and for not being negative or zero depending on your requirements is enough .

Numeric types in programming languages do not have leading zeroes. But string representations might have. If you have a string representing a number and that must contain leading zeroes, you can use the strtol - C++ Reference[^] function:
C++
// Skip any non-digits because strtol will skip leading white spaces
//  and accept signs. This won't work for negative numbers.
while (*szInput && !isdigit(*szInput))
    ++szInput;
char *stop;
long num = strtol(szInput, &stop, 10);
if (stop - szInput == 3)
{
    // Has three digits
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900