String to Integer Conversion

If you use Borland C++ and you want to use the value of a string as an integer, you can use the AnsiString::ToInt() method. 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:

int N1 = Edit1->Text.ToInt();
int N2 = Edit2->Text.ToInt();
int Subt = N1 - N2;

Edit3->Text = Subt;

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:

int Value1 = Edit1->Text.ToIntDef(0);
int Value2 = Edit2->Text.ToIntDef(1);

A function used to convert a string is also the StrToInt() function:

int Number1 = StrToInt(Edit1->Text);
int Number2 = StrToInt(Edit2->Text);

int Addition = Number1 + Number2;
Edit3->Text = Addition;


One thought on “String to Integer Conversion

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s