如果我想将“001”之类的数字视为3位数字,如何检查输入是否为整数变量“a”的3位数字? [英] 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?

查看:170
本文介绍了如果我想将“001”之类的数字视为3位数字,如何检查输入是否为整数变量“a”的3位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在制作一个C ++文件处理项目。它中有这个变量:int roll。

它应该有3位数。我想过使用像if(roll> 99 || roll< 1000)这样的方法,但它没用。它显然是091作为2位数字,003作为1位数字。那么,如果我想将像'001'这样的数字视为3位数字,如何检查输入是否是整数变量'a'的3位数字?



我尝试过:



我想过使用像if这样的方法(roll> 99 || roll< 1000 )但它没用。它显然需要091作为2位数字,003作为1位数字。

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.

推荐答案

这取决于:如果你正在读取文件中的值,那么你会需要做你显示的if测试,几乎。

如果你生成一个随机数(名称 roll 暗示你是),那么生成0到899之间的随机数,然后加100。这样,你可以保证一个非零最重要数字的值。



如果没有相关的代码片段,我们可以说 - 有太多不同你可以做的事情!
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!


如果它是一个整数变量,检查< 1000 并且根据您的要求不是负数或零是足够的。



编程语言中的数字类型没有前导零。但字符串表示可能有。如果您有一个表示数字的字符串且必须包含前导零,则可以使用 strtol - C ++参考 [ ^ ]功能:

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:
// 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
}


这篇关于如果我想将“001”之类的数字视为3位数字,如何检查输入是否为整数变量“a”的3位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆