最近写了个小程序用到了CListCtrl控件。控件显示的内容随着程序的运行动态增加,然而程序的内容偶尔会出现乱码。为了便于确定是否是传参有问题,我将显示控件上的内容写回文件,发现文件显示一切正常。调用增加记录的函数如下:
void AddRecord(DWORD in_time,DWORD out_time,DWORD64 id, float charge)
{
   CString write_record;
   CString temp;    write_record.Empty();
   temp.Empty();
       
   if(m_data_index==0)                 //第一项记录
   m_data_index=1;
   temp.Format("%d",m_data_index);
          ((CListCtrl*)GetDlgItem(IDC_LIST_RECORD))->InsertItem(index,(LPCTSTR)temp);
   write_record+=temp;    temp.Empty();                      //第二项记录
   CTime time;
   if(in_time>0) 
   {
   time=((time_t)in_time);
     temp=time.Format("%Y-%m-%d %H:%M:%S");
   }
   else
   temp="未知时间";      ((CListCtrl*)GetDlgItem(IDC_LIST_RECORD))->SetItemText(index,1,(LPCTSTR)temp);//
   write_record+="\t";
   write_record+=temp;
 
   temp.Empty();                       //第三项记录
   if(leave_time>0)
   {
   time=((time_t)out_time);
     temp=time.Format("%Y-%m-%d %H:%M:%S");
}
   else
   temp="未知时间";
   ((CListCtrl*)GetDlgItem(IDC_LIST_RECORD))->SetItemText(index,2,(LPCTSTR)temp);//
   write_record+="\t";
   write_record+=temp;    temp.Empty();                      //第四项记录
   temp.Format("%d",id);  
   ((CListCtrl*)GetDlgItem(IDC_LIST_RECORD))->SetItemText(index,3,(LPCTSTR)temp);//
   write_record+="\t";
   write_record+=temp;
   if(charge<0)                      //第五项记录
   charge=0;
   temp.Empty();
   temp.Format("%.2f",charge);
   ((CListCtrl*)GetDlgItem(IDC_LIST_RECORD))->SetItemText(index,6,(LPCTSTR)temp);
   write_record+="\t";
   write_record+=temp;
   write_record+="\t\r\n";           WriteFileRecord(write_record);   //写记录文件
   index++;
   m_data_index++;    write_record.Empty();
   temp.Empty();
}
乱码程序的形式有如下几种:
1.显示的位置不对
2.有时显示的内容为空,再随着程序运行又会莫名奇妙的显示乱码
3.直接显示奇特的字符

解决方案 »

  1.   

    说实话看你的代码好费尽啊,
    变量index,m_data_index有点可疑,建议好好跟踪一下
      

  2.   

    我是新手,代码还没怎么精炼。
    int index //表示CListCtrl的插入项的序号
    int m_data_index  //表示显示在CListCtrl中的第一项的内容 
    CString write_record;  //表示要写入文件的内容
    CString temp; //表示在CListCtrl中要显示的内容字符串无论程序运行多久(>30天,500条/天)文件中显示的内容准确无误,但是CListCtrl却有很多乱码
    也就是说 上述变量应该没有什么问题吧
      

  3.   

    //SetItemText(index,6,(LPCTSTR)temp);
    SetItemText(index,6,temp);这样看看可以不,应该和这个没关系了
    还有index的值是在怎么赋值的阿,能简单给出代码么
      

  4.   

    temp.Empty();
    最好全部改成
    temp = _T("");
      

  5.   

    index在类的初始化,也就是在程序启动时为零。随着记录增加而增加。换了_T("")还是不可以持续等待解决中.....
      

  6.   

    错误终于找出来了,在程序中和CListCtrl毫无相关的一个数组溢出了。
    原来数组越界,程序还能高频率跑几天都不死。
    还是要感谢以上各位的关注。