Hi everyone,

I need help with this one problem. I'm using Visual C++ 2008, Windows Forms app, and I've created a test program where you can set up two system::strings, xvalue and yvalue. It then converts them to Ints (x and y). It then calculates x and y depending on the radiobutton you select (+. -, /, x). After calculating, it converts it back to a system::string and displays it on a textbox, for the user to see his result of the calculation.


Variables:

String^ xvalue;
String^ yvalue;
String^ resultstr;

int method;
int x;
int y;

Main code:

private: System::Void btnX_Click(System::Object^  sender, System::EventArgs^  e) {
//sets xvalue's text from the user's input
xvalue = this->txtX->Text;
//Parses (converts) xvalue(string) to int x(int)
int x =  System::Int32::Parse(xvalue);
this->txtX->Visible = false;
this->btnX->Visible = false;
MessageBox::Show(L"X was set.");
}

private: System::Void btnY_Click(System::Object^  sender, System::EventArgs^  e) {
//sets yvalue's text from the user's input
yvalue = this->txtY->Text;
//Parses (converts) yvalue(string) to int y(int)
int y =  System::Int32::Parse(yvalue);
this->txtY->Visible = false;
this->btnY->Visible = false;
MessageBox::Show(L"Y was set.");
}

//If the '+' Radiobutton is checked
if(this->radioButton1->Checked == true)
 if(this->radioButton2->Checked == false)
  if(this->radioButton3->Checked == false)
   if(this->radioButton4->Checked == false)
   {
    //int method's value is x + y
    method = x + y;

    //Convert method to system::string, and display it on the txtresult textbox, which is where the user sees the result of the calculation.
    txtresult->Text = Convert::ToString(method);
    }

This all compiles properly, but, when it displays in the txtresult textbox, the answer to every equation is 0. Can someone help me out here? (sry, I'm such a noob at C++ :()

See your code sceleton:

int method;
int x;
int y;
...
private: System::Void btnX_Click(...)
{ 
...
int x =  System::Int32::Parse(xvalue);
// Oops! you have local variable x, not outer x...
...
} // Bye, local (automatic) x with calculated result...
...
private: System::Void btnY_Click(...)
{
...
int y =  System::Int32::Parse(yvalue);
// The same trick with local y: hide outer y, save value then die...
}
...
method = x + y;
// Sum of intacted x and y...

That's all, folks. Be careful with context (scope) games.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.