2013-10-13 62 views
1

我已經制作了一個帶有3個文本框的Windows窗體應用程序。爲了使程序工作,我需要用三個數字填充所有三個框。它們可以是正數也可以是負數。C++/cli檢查數值是否爲

我用這個:

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

以檢查框被填滿,但我無法弄清楚如何顯示錯誤消息,如果有喜歡的字母或其他什麼東西的象徵,從不同數。

回答

2

我假設你真正想做的事與數字的東西嗎?

所以對於轉換失敗測試:

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,所以不需要對空字符串進行單獨測試。

+0

謝謝。 這與int一起工作,但是當我輸入類似2.5的東西時,我得到了錯誤: – user2765257

+0

@ user2765257:我之前使用TryParse作爲雙打而沒有問題,所以我建議你再看看你的代碼,你可能不會轉換你的想法。 –

+0

所以這就是我得到的錯誤: 'number = System :: Convert :: ToInt32(this-> textBox1-> Text);' TryParse傳遞此編號,但當我嘗試轉換它時程序中斷。 – user2765257

1

使用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)); 
    } 
} 
+1

C#語法泄漏到您的C++? –

+0

那個放錯了'out'的令牌仍然在那裏... –