kenlistian

厚积薄发. 勤为桨,思为帆

   :: 首页 :: 新随笔 ::  :: 聚合  :: 管理 ::
  73 随笔 :: 4 文章 :: 22 评论 :: 0 Trackbacks

    MFC中CEdit多行情况下,调用GetLine()时,发现老是后面跟有乱码。即使你把str初始化也是如此。

对于采用GetLine()调用,其函数说明有2种。

1.int GetLine(
   int nIndex,
   LPTSTR lpszBuffer 
) const;
2.int GetLine(
   int nIndex,
   LPTSTR lpszBuffer,
   int nMaxLength 
) const;

  代码如下:

   char str[10] = {'\0'};
   int nLineNum;//想要获取的行号
   nLineNum=0;
   m_ctlEditTest.GetLine(nLineNum,str);

Remarks : The copied line does not contain a null-termination character.

看了下msdn,一句话说得很明白,getline做了copy后是不给你加null结束符的。因此需要自己在定义的char字符串末尾添加。而一次实际上会copy回多少个字节。则在该函数的说明中,在msdn中清晰表达为:

Return Value

  The number of bytes actually copied. The return value is 0 if the line number specified by nIndex is greater than the number of lines in the edit control.

所以,上面的代码段得用一个值取得实际长度,把多余的截取掉,但我在用getline1时老是返回0,不知道为何?不过改成getline2,指定copy9个字节时,同时对第10个字节设置为null则正常返回,没有乱码的出现。如下

  int iLen =  m_ctlEditTest.GetLine(nLineNum,str, 9);

  str[10] = '\0'; 

即可。

。。。。。。。

在cedit中还有个linelength函数,

int LineLength(
   int nLine = -1 
) const;

该函数是应该返回指定行的长度,但是如果不仔细看msdn的说明,很容易误解nLine是指cedit行中的某一行行数而代入其中,并得到错误的结论。

而在msdn中,nLine的说明是:

nLine

Specifies the character index of a character in the line whose length is to be retrieved. If this parameter is –1, the length of the current line (the line that contains the caret) is returned, not including the length of any selected text within the line. When LineLength is called for a single-line edit control, this parameter is ignored.

就是说nLine是字符串的字符索引,在多行情况下所以它必须通过LineIndex函数来获取。在msdn中如下描述,

   Use the LineIndex member function to retrieve a character index for a given line number within a multiple-line edit control.

而LineIndex函数说明如下:

all this function to retrieve the character index of a line within a multiple-line edit control.

int LineIndex(
   int nLine = -1 
) const;

nLine

Contains the index value for the desired line in the text of the edit control, or contains –1. If nLine is –1, it specifies the current line, that is, the line that contains the caret.

该nLine才是真正的CEdit中的某一行列。也就是我们通过getlinecount()获取到cedit的行数后,在到每一行中去找一个character index,再才能确定一行的长度。

有时,觉得mfc是不是有点对个简单的问题把弯子绕得太远了点吧。

。。。。

下面摘抄另一种解决方案,采用CString方式来copy一行的长度,我在自己机子测试过,通过GetLine函数1没有通过,返回的是个空串,而采用GetLine2指定返回一个最大长度时,却能copy回所要的数据,不过当采用最大长度时,由于拷贝回来的是一个不带null终结符的串,则存在乱码。由于工作时间紧张,问题只能采用指定大小的char串处理,但是采用CString串如果不指定大小的方法做一个mark。下列代码供测试参考。

CString strTemp;
int nLineNum;
nLineNum=0;
m_ctlEditTest.GetLine(nLineNum,strTemp.GetBufferSetLength(m_ctlEditTest.LineLength(m_ctlEditTest.LineIndex(nLineNum))));
strTemp.ReleaseBuffer();

。。。。。。

总而言之,感觉vc中mfc太过于细节,莫免麻烦。但是感觉经历过一次后,就不再是磕脚的石头,而是心态的放心。也许,这是心理作用而已。

posted on 2008-02-15 21:17 kenlistian 阅读(5422) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理