获取edit ctrl中的每一行的字符串内容,发现MSDN上如下的代码:
#ifdef _DEBUG
// The pointer to my edit.
extern CEdit* pmyEdit;
int i, nLineCount = pmyEdit->GetLineCount();
CString strText, strLine;
// Dump every line of text of the edit control.
for (i=0;i < nLineCount;i++)
{
pmyEdit->GetLine(i, strText.GetBuffer(pmyEdit->LineLength(i)));
strText.ReleaseBuffer();
strLine.Format(TEXT("line %d: '%s'/r/n"), i, strText.GetBuffer(0));
afxDump << strLine;
}
#endif
结果却总出错,后来发现,这段代码有误,在MSDN里关于CEdit::LineLength有这样的说明:
Call this function to retrieve the length of a line in an edit control. Use the LineIndex member function to retrieve a character index for a given line number within a multiple-line edit control.
再根据MSDN里关于CEdit::GetLineCount 的说明:GetLineCount is only processed by multiple-line edit controls可知上述代码应该是用在多行编辑框中的,所以上述代码应该做如下修正:
将LineLength(i) 修改为 LineLength(pmyEdit->LineIndex(i))
另附我当时的解决方法:
CString m_strTemp;
//-------------------//
DDX_Text(pDX, IDC_EDIT1, m_strTemp);
//-------------------//
UpdateData(TRUE);
CString tempstr = m_strTemp;
int index = -1;
CStringArray linesArray;
linesArray.SetSize(5);
linesArray.RemoveAll();
while((index = tempstr.Find("/r/n")) >= 0)
{
CString strCurr = tempstr.Left(index);
linesArray.Add(strCurr );
//AfxMessageBox(strCurr );
tempstr = tempstr.Right(tempstr.GetLength() - index - 2);
}
if(tempstr.GetLength() > 0)
{
linesArray.Add(tempstr);
//AfxMessageBox(tempstr);
}
CEdit中有一个GetLine()方法,可以读取一行数据,可以其中的第二个参数是LPTSTR型的,一般我们希望读取后赋给一个CString型的变量。
所以如果直接赋给LPTSTR可能会有点麻烦。
查资料可以知道LPTSTR一般也就相当于char*,所以我们可以使用GetLine将读取到的值赋给一个char。
char str[10];
int nLineNum;//想要获取的行号
nLineNum = 0;
m_strTemp.GetLine(nLineNum, str);
但char型要事先声明大小,在不知道该行数据长度的情况下我们比较难控制char的大小。
所以读取的数据可能不是很理想,这样子后面会出现乱码。
我们可以换一种方法,直接使用CString读取。
CString strTemp;
int nLineNum;
nLineNum = 0;
m_strTemp.GetLine(nLineNum, strTemp.GetBufferSetLength(m_strTemp.LineLength(m_strTemp.LineIndex(nLineNum))));
strTemp.ReleaseBuffer();
LineLength()用于获取某一行的数据长度,但你不能直接对它赋行号,查询MSDN可以看到这样一段话:
Use the LineIndex member function to retrieve a character index for a given line number within a multiple-line edit control.
当我们想要获取多行文本控件的内容时,需要使用LineIndex成员函数所以我们需要通过LineIndex来得到行号,最后使用GetBufferSetLength来改变CString对象的大小。这样子就可以顺利读取某一行的数据了。
int nLineNum, nLineCount = ((CEdit *)GetDlgItem(IDC_EDIT3))->GetLineCount();//得到行数
CString strText, strLine;
for (nLineNum=0; nLineNum<nLineCount; nLineNum++)
{
((CEdit *)GetDlgItem(IDC_EDIT1))->GetLine(nLineNum, strText.GetBufferSetLength(((CEdit *)GetDlgItem(IDC_EDIT1))->LineLength(((CEdit *)GetDlgItem(IDC_EDIT1))->LineIndex(nLineNum))));
strText.ReleaseBuffer();
strLine.Format(TEXT("第%d行: '%s' 字符个数: %d/r/n"), nLineNum+1, strText.GetBuffer(0), strText.GetLength());
MessageBox(strLine);
}