简体   繁体   English

如何在C ++中检查来自editText的输入是否为整数

[英]How To Check the Input from editText is integer in C++

I want to validate the input from Edit Text, if the input is not integer, Message Box or Show Message will appear, i use 我想验证来自“编辑文本”的输入,如果输入不是整数,则会出现“消息框”或“显示消息”,我使用

if(input->Text.ToIntDef(1)){
  //instruction
}

but when i run the app, if condition always true , even though i input integer in the Edit Text(i input 5000, 4500, 7000, 7500, 2000, 2500) 但是当我运行应用程序时, if条件始终为true ,即使我在编辑文本中输入了整数(我输入了5000、4500、7000、7500、2000、2500)

A simple method, could be to scan the content of the string, if you detect anything that is not a digit, you can stop the scan and assume that the number is not an integer. 一种简单的方法可能是扫描字符串的内容,如果您检测到不是数字的任何内容,则可以停止扫描并假定该数字不是整数。

bool is_integer(const char* input) {
    while(*input) {
        if (*input < '0' ||  *input > '9') {
            return false;
        }
        ++input;
    }
    return true;
}

The simple approach above considers an empty string an integer as well, it is a simple matter to change that. 上面的简单方法也将空字符串也视为整数,更改它很简单。 Further more any white space in the input will cause the function to treat the input as not being an integer, if you want white spaces to be ignored, you can trim the input before passing it to the function. 此外,输入中的任何空白都会使函数将输入视为不是整数,如果希望忽略空格,则可以在将输入传递给函数之前对其进行修剪。

From your example I get a suspicion that you are using the VCL-like framework: FireMonkey from C++ Builder, this framework has a method on its default string class called ToInt as far as I recall (without the Def suffix) which will attempt to parse the string as an integer, if unable to, it will throw an EConvertError exception, which you can then basically just catch. 从您的示例中,我怀疑您使用的是类似VCL的框架:C ++ Builder中的ToInt ,据我回忆(不带Def后缀),该框架在其默认字符串类上有一个名为ToInt的方法,该方法将尝试解析。字符串作为整数,如果无法执行,将抛出EConvertError异常,然后可以基本上捕获该异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM