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.

Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92

3 Answers3

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.

Dmitry Arestov
  • 1,427
  • 12
  • 24
  • 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. – BeginnerWin32 Apr 01 '15 at 13:23
  • 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. – Dmitry Arestov Apr 01 '15 at 13:43
  • Of course. If `m_Result` is associated with text box, you should call `UpdateData(FALSE)` to propagate the result into text box. – Dmitry Arestov Apr 01 '15 at 13:49
1

Use

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

Or

num = atoi((char*)(LPCTSTR)strNum);  
Himanshu
  • 4,327
  • 16
  • 31
  • 39
-1

The correct UNICODE compliant way of doing this:

CString str = _T("10");
int nVal = _ttoi(str);
__int64 = _ttoi64(str);
Andrew Komiagin
  • 6,446
  • 1
  • 13
  • 23