About CEdit::LineLength

以前想获取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_editcontent;
//-------------------//
 DDX_Text(pDX, IDC_EDIT1, m_editcontent);
//-------------------//
 UpdateData(TRUE);

 CString tempstr = m_editcontent;

 int index = -1;

 CStringArray linesArray;
 linesArray.SetSize(5);
 linesArray.RemoveAll();

 while((index = tempstr.Find("\r\n")) >= 0)
 {
  CString curline = tempstr.Left(index);
  linesArray.Add(curline);
  //AfxMessageBox(curline);
  tempstr = tempstr.Right(tempstr.GetLength() - index - 2);
 }
 if(tempstr.GetLength() > 0)
 {
  linesArray.Add(tempstr);
  //AfxMessageBox(tempstr);
 }


---->>"冰蓝色的小屋"主人的解决方案<<----

读取CEdit中某一行数据的方法

搞了一上午,终于搞清楚了怎样读取CEdit中一行的数据,才发现数据类型转换真是伤脑筋。

CEdit中有一个GetLine()方法,可以读取一行数据,可以其中的第二个参数是LPTSTR型的,一般我们希望读取后赋给一个CString型的变量。
所以如果直接赋给LPTSTR可能会有点麻烦。
查资料可以知道LPTSTR一般也就相当于char*,所以我们可以使用GetLine将读取到的值赋给一个char。
char str[10];
int nLineNum;//想要获取的行号
nLineNum=0;
m_ctlEditTest.GetLine(nLineNum,str);

但char型要事先声明大小,在不知道该行数据长度的情况下我们比较难控制char的大小。
所以读取的数据可能不是很理想,这样子后面会出现乱码。

我们可以换一种方法,直接使用CString读取。
CString strTemp;
int nLineNum;
nLineNum=0;
m_ctlEditTest.GetLine(nLineNum,strTemp.GetBufferSetLength(m_ctlEditTest.LineLength(m_ctlEditTest.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对象的大小。
这样子就可以顺利读取某一行的数据了。

posted on 2005-10-11 16:58  vcfly  阅读(2201)  评论(3编辑  收藏  举报