2

I am just a beginner to MFC platform. I am just trying a simple pgm. Getting 2 numbers in 2 edit boxes and displaying the sum in the third edit box when a button is clicked.

This is my code:

void CMineDlg::OnEnChangeNumber1()
{
   CString strNum1,strNum2;
   m_Number1.GetWindowText(strNum1,10);   //m_NUmber1 is variable to 1st edit box.
   m_Number2.GetWindowText(strNum2,10);   //m_Number2 is variable to 2nd edit box.
} 

void CMineDlg::OnBnClickedSum()
{
   m_Result=m_Number1+m_Number2;
}

I know I have to convert the strings to integer. But I have no idea how to do it. Pls Help.

1
  • If there s some thread related to this pls post it her. I didnt find it. Pls help. Commented Apr 1, 2015 at 13:43

3 Answers 3

2

You can use Class Wizard to add variables of integer type and associate them with edit boxes. Then, in OnEnChangeNumber1 event handler (or in OnBnClickedSum), you simply call UpdateData(TRUE); which causes those variables to update their values. After that, you can sum those integer variables.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply.. I have created integer variables for edit boxes and associated them with the edit boxes. In Button Event handler I have added the two numbers. There is no error in it. But when it is executed the first edit box is displaying 0 and the second is displaying -858993460 and the result edit box is showing -858993460 even without the button is clicked. I want to get user input using GetWindowText. So the input will be in string type. Also pls help in string to integer conversion.
As for strange negative values, you should initialize your integer variables before showing the dialog. You can do this in the constructor or in the OnInitDialog method. Again, you don't need to convert strings to integers and vise versa. MFC will do it for you. When you call UpdateData(TRUE), MFC internally takes string values from text boxes via GetWindowsText and converts them to appropriate types of your associated variables. When you call UpdateData(FALSE), MFC converts your associated variables to strings and populates text boxes.
Of course. If m_Result is associated with text box, you should call UpdateData(FALSE) to propagate the result into text box.
1

Use

CString strNum = _T("11");  //CString variable
int num;                //Integer Variable
_stscanf(strNum, _T("%d"), &num);   //Conversion

Or

num = atoi((char*)(LPCTSTR)strNum);  

1 Comment

This is not UNICODE compliant
-1

The correct UNICODE compliant way of doing this:

CString str = _T("10");
int nVal = _ttoi(str);
__int64 = _ttoi64(str);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.