Jump to content
357mag

Need to convert a string number to an integer

Recommended Posts

I need to convert a number (which I think defaults to a string) to an integer in C++ Builder:

 

void __fastcall TForm1::Button1Click(TObject *Sender)
{
	int x;
	int y;
	int sum;

	x = std::stoi (Edit1->Text);
	y = Edit2->Text;

	sum = x = y;

	Label3->Caption = "The sum is" + sum;

 

Edited by 357mag

Share this post


Link to post

Well I think I got part of it going.

 

    y = Edit2->Text.ToInt();

 

I think that is okay, but the answer in the Label just says "is". I think I got the same problem going on. Pointer arithmetic or something. I'll have to mess with it.

Share this post


Link to post

"It worked" does not mean that the code is sensible or ideal. You don't need / want to convert the int value called sum to an AnsiiString. you actually want to convert it to a C++ Builder String type (whichi is actually a UnicodeString). So you would be better to have used 

Label3->Caption = String("The sum is ") + String(sum);

Share this post


Link to post

Also for simple conversions from String types to integer types you may like to use the ToIntDef() String member function. Pass this a default value which is the value returned if the String variable does not contain a valid integer.  (The ToInt() function throws an exception if the String cannot be converted to an integer).

Share this post


Link to post
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	int x = Sysutils::StrToInt(Edit1->Text);
	// alternatives:
	// int x = Edit1->Text.ToInt();
	// int x = std::stoi(Edit1->Text.c_str());
	// int x = CSpinEdit1->Value; (using a TCSpinEdit instead of a TEdit)

	int y = Sysutils::StrToInt(Edit2->Text);
	// same as above...
  
	int sum = x + y;

	Label3->Caption = _D("The sum is ") + String(sum);
	// alternatives:
	// Label3->Caption = Sysutils::Format(_D("The sum is %d", ARRAYOFCONST((sum)) );
	// Label3->Caption = String{}.sprintf(_D("The sum is %d", sum);
	// Label3->Caption = std::format(L"The sum is {}", sum).c_str();
	// Label3->Caption = (std::wostringstring{} << L"The sum is " << sum).str().c_str();
}

 

Edited by Remy Lebeau

Share this post


Link to post

In order not to piss anyone off on the forum, I will change my code to the C++ Builder string type. 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×