Home

Math Functions

 

String to Integer Conversion

If you want to use the value of a string as an integer, you can use the AnsiString::ToInt() method. Its syntax is:

int __fastcall ToInt() const;

This member function converts an AnsiString variable to a valid integer. In the following example, the contents of two edit boxes are converted to integers and a subtraction is performed:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	int Number1 = Edit1->Text.ToInt();
	int Number2 = Edit2->Text.ToInt();
	int Subtract = Number1 - Number2;
	
	Edit3->Text = Subtract;
}
//---------------------------------------------------------------------------

If the control whose string needs to be converted is displaying an invalid integer, the program would throw an error. The AnsiString provides a viable alternative. The AnsiString::ToIntDef() method allows you to supply a default value if the conversion fails. Here is an example that uses it:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	int Value1 = Edit1->Text.ToIntDef(0);
	int Value2 = Edit2->Text.ToIntDef(1);
	
	int Remainder = Value1 % Value2;
	Edit3->Text = Remainder;
}
//---------------------------------------------------------------------------

A function used to convert a string is the StrToInt() function. Its syntax is:

int __fastcall StrToInt(const AnsiString S);

This function takes as an argument the string that you are trying to convert. In the following example, the strings of two edit boxes are converted to integers and an addition is performed on their values:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	int Number1 = StrToInt(Edit1->Text);
	int Number2 = StrToInt(Edit2->Text);
	
	int Addition = Number1 + Number2;
	Edit3->Text = Addition;
}
//---------------------------------------------------------------------------
 
Home Copyright 2004 FunctionX, Inc.