Converting textbox string to float?

可紊 提交于 2019-12-31 03:35:07

问题


I'm basically trying to write a basic converter in visual studio 2008, and I have 2 text boxes, one which gets input from the user, and one which gives output with the result. When I press the button I want the input from the first textbox to multiply by 4.35 then display in the 2nd textbox. This is my code in the button code so far:

             String^ i1 = textBox1->Text;
             float rez = (i1*4.35)ToString;
             textBox2->Text = rez;

However I'm getting these errors:

f:\microsoft visual studio 9.0\projects\hellowin\hellowin\Form1.h(148) : error C2676: binary '*' : 'System::String ^' does not define this operator or a conversion to a type acceptable to the predefined operator
f:\microsoft visual studio 9.0\projects\hellowin\hellowin\Form1.h(148) : error C2227: left of '->ToString' must point to class/struct/union/generic type
f:\microsoft visual studio 9.0\projects\hellowin\hellowin\Form1.h(149) : error C2664: 'void System::Windows::Forms::Control::Text::set(System::String ^)' : cannot convert parameter 1 from 'float' to 'System::String ^'

Please help I'm going insane on how ridiculously difficult it is to get some input from a textbox in C++. I've googled every error I had and nothing useful came up, I've been searching answers for an hour already, please help.


回答1:


Fixing it for you,

         String^ i1 = textBox1->Text;
         float rez = (float)(Convert::ToDouble(i1)*4.35);
         textBox2->Text = rez.ToString();

Basically, you want to convert your string to an actual number, do the math, and then make it back into a string for displaying purposes.




回答2:


You're trying to multiply a string by a double and there is no operator that defines how to do that. You need to convert your string to a double first, and then use that in the calculation.

Then, you're trying to assign a string to a float, which again is nonsense.. You need to calculate the float, then convert it to a string when assigning it to the textbox text field.

Something like:

String^ i1 = textBox1->Text;
float rez = (Convert::ToDouble(i1)*4.35);
textBox2->Text = rez.ToString();


来源:https://stackoverflow.com/questions/8718048/converting-textbox-string-to-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!