I have the following code, m_edit is a MFC CEdit (I know I would never use MFC but project demanded it).
It's a simple loop, that gets the text from a text edit, converts it to integer after getting the first line, then stores it in m_y vector.
LPTSTR szTemp;
vector<int> m_y;
for(int i = 0; i < m_edit->GetLineCount(); i++){
szTemp = s_y.GetBuffer(0);
m_edit->GetLine(i, szTemp); // get line text store in szTemp
y = atoi(szTemp);
m_y.push_back(y);
szTemp = "";
y = 0;
}
IMPORTANT EXAMPLE: So let's say the CEdit has 6 numbers:
If you use Visual Studio's debugger you will notice an anomaly!! Here's what it shows:
Do you see that? szTemp when inserted into atoi, it returns the number 6, but concatenates the 2nd digit of the last number!!! This is why I did szTemp = "";, but the problem persists. Also, let's say the last number was 17 (not 18), then this time debugger would say y = 67, so it is definitely this problem.
However, Visual Studio debugger, when you hover over szTemp during this iteration, it says '6' <--- not '68' inside szTemp. So somehow atoi is ruining it.
Am I suppose to concatenate a \0 into szTemp before putting it into atoi? How do I solve this easily?
From the MFC CEdit::GetLine documentation:
Remarks: The copied line does not contain a null-termination character.
So you need to pay attention to GetLine
's return value to determine how many bytes were copied into the buffer and then add your own NUL-terminator.
Also, I would recommend that you pass in the buffer size to make sure you don't have a potential buffer overflow.