357mag 2 Posted May 20, 2023 (edited) 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 May 20, 2023 by 357mag Share this post Link to post
357mag 2 Posted May 20, 2023 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
Roger Cigol 103 Posted May 22, 2023 "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
Roger Cigol 103 Posted May 22, 2023 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
Remy Lebeau 1393 Posted May 22, 2023 (edited) 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 May 22, 2023 by Remy Lebeau Share this post Link to post
357mag 2 Posted May 23, 2023 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