C++/CLI 检查值是否为数字

c++/cli check if value is number

本文关键字:是否 数字 检查 CLI C++      更新时间:2023-10-16

我做了一个带有3个文本框的Windows表单应用程序。为了使程序正常工作,我需要用数字填充所有三个框。它们可以是积极的,也可以是消极的。

我用了这个:

if(this->textBox1->Text=="" || this->textBox2->Text=="" || this->textBox3->Text=="") {
    MessageBox::Show("Error");
}
else {
    // continue with the program...
}

检查框是否已填充,但如果有一个符号,如字母或其他东西,与数字不同,我无法弄清楚如何显示错误消息。

我假设你真的想用数字做点什么?

因此,测试转换失败:

int number1;
if (!int::TryParse(textBox1->Text, number1)) {
    MessageBox::Show("First box wasn't an integer");
    return;
}
double number2;
if (!double::TryParse(textBox2->Text, number2)) {
    MessageBox::Show("Second box wasn't numeric");
    return;
}

最后,您有number1number2的数字,以便在计算中使用。

您将不再需要对空字符串进行单独的测试,因为如果输入为空TryParse将返回 false。

使用 Double.TryParse()

Double x;
array<TextBox^>^ inputs = gcnew array<TextBox^>(3);
inputs[0] = this->textBox1;
inputs[1] = this->textBox2;
inputs[2] = this->textBox3;
for (int i = 0; i < inputs->Length; i++)
{
    if(!Double::TryParse(inputs[i]->Text, x))
    {
        MessageBox::Show("Error", String::Format("Cannot parse textBox{0} as number", i+1));
    }
}