VC++常用代码总结

//设置某个控件内容的样式
     myfont.CreatePointFont(250, "宋体");
     GetDlgItem(IDC_EDIT4)->SetFont(&myfont);
//设置ListCtrl控件样式
     m_ListResult.InsertColumn(1,"工作内容",LVCFMT_LEFT,324,5);
     m_ListResult.InsertColumn(2,"工作进度",LVCFMT_LEFT,70,5);
     m_ListResult.SetExtendedStyle(LVS_EX_GRIDLINES| LVS_EX_INFOTIP|LVS_EX_FLATSB|LVS_EX_HEADERDRAGDROP|LVS_EX_MULTIWORKAREAS);
//为控件初始化值
     GetDlgItem(IDC_EDIT1)->SetWindowText("FIH-MSEG-IT");
//获取某个全局变量的值,namelogin是在CContentsSubmitApp中定义的全局变量
     CString nameloginname=(( CContentsSubmitApp *)AfxGetApp())->namelogin;
GetDlgItem(IDC_EDIT2)->SetWindowText(nameloginname);
     //Combol组合框赋初始值,其中m_weekContral型变量
     CString ww,istr;
     for(int i=1;i<53;i++)
     { //一年有52周
         istr.Format("%d",i);//先将i值转化为cstring型
         ww="第"+istr+"周"; //不能直接写成ww="第"+i+"周"
         m_week.AddString(ww);
     }
    //设置树型控件样式
HTREEITEM hItem1=m_Tree.InsertItem(_T("系统开发课"),0,1);
HTREEITEM hItem11=m_Tree.InsertItem(_T("应用程式开发"),0,1,hItem1,TVI_LAST);
              m_Tree.InsertItem(_T("jts"),0,1,hItem11,TVI_LAST);
  HTREEITEM hItem12=m_Tree.InsertItem(_T("WEB程式开发"),0,1,hItem1,TVI_LAST);
             m_Tree.InsertItem(_T("wjh"),0,1,hItem12,TVI_LAST);
HTREEITEM hItem2=m_Tree.InsertItem(_T("系统维护课"),0,1);
        HTREEITEM hItem21=m_Tree.InsertItem(_T("系统维护课A组"),0,1,hItem2,TVI_LAST);
            m_Tree.InsertItem(_T("wc"),0,1,hItem21,TVI_LAST);    
       HTREEITEM hItem22=m_Tree.InsertItem(_T("系统维护课B组"),0,1,hItem2,TVI_LAST);
            m_Tree.InsertItem(_T("lzp"),0,1,hItem22,TVI_LAST);   
//获取组合框的选中项,其中m_week为Contral型值,m_vweek为控件的value型值
int nsel=m_week.GetCurSel();
     if(nsel==CB_ERR)
     {
AfxMessageBox("没有选周会梯次");
         return;
     }
     m_week.GetLBText(nsel,m_vweek);
 
//树型控件双击事件
void CContentsSubmitDlg::OnDbClickTree(NMHDR* pNMHDR,LRESULT* pResult)
{
     m_hTreeItem = m_Tree.GetSelectedItem();
     CString sname = m_Tree.GetItemText(m_hTreeItem);
     AfxMessageBox("You have selected "+S1);
     *pResult = 0;
}
//将多条记录插入到Listctrl控件
ADOconn m_conn;    _RecordsetPtr m_pRecordset;
CString s_Conn="Provider=SQLOLEDB;Server=10.128.128.221;Database=Eink;uid=stone;pwd=stone";
vSQL="select workcontents,schedule,completedate from contens where employee='"+sname+"' and week='"+m_vweek+"'";
m_conn.OnInitADOConn(s_Conn);        m_pRecordset=m_conn.GetRecordSet(vSQL);
int justitem=0,k=0;
m_ListResult.DeleteAllItems();//将listctl控件的值清空
m_ListResult.SetTextColor(RGB(255,0,255));//设置控件内容的颜色
//if(!m_pRecordset->ADOEOF)不能改成这样,否则只显示一行
if(!m_pRecordset->ADOEOF)
{   while(!m_pRecordset->ADOEOF)
{
vResult[0]=m_pRecordset->GetCollect(_variant_t((long)0));
     vResult[1]=m_pRecordset->GetCollect(_variant_t((long)1));
     vResult[2]=m_pRecordset->GetCollect(_variant_t((long)2));
     CString work=(LPCTSTR)(_bstr_t)vResult[0];
     CString sche=(LPCTSTR)(_bstr_t)vResult[1];
     CString compl=(LPCTSTR)(_bstr_t)vResult[2];
     justitem=this->m_ListResult.InsertItem(k,work);//m_ListResult第0列第k行插入测试项目信息
     this->m_ListResult.SetItemText(justitem,1,sche);//m_ListResult第1列插入测试结果信息
     this->m_ListResult.SetItemText(justitem,2,compl);//m_ListResult第1列插入测试结果信息
     this->m_ListResult.SetItemText(justitem,3,sname);//m_ListResult第1列插入测试结果信息
     m_pRecordset->MoveNext();
     k++;
 }
}
else
{
     m_ListResult.SetTextColor(RGB(255,0,0));
     justitem=this->m_ListResult.InsertItem(0,"未填写");//m_ListResult第0列插入测试项目信息
     this->m_ListResult.SetItemText(justitem,1,"未填写");//m_ListResult第1列插入测试结果信息
     this->m_ListResult.SetItemText(justitem,2,"未填写");//m_ListResult第1列插入测试结果信息
     this->m_ListResult.SetItemText(justitem,3,"未填写");//m_ListResult第1列插入测试结果信息
}
     m_conn.ExitConnect();

************************************************************************************************************************************

//ListCtrl控件单击事件,重载函数
void CContentsSubmitDlg::OnNMClickList1(NMHDR *pNMHDRLRESULT *pResult)
{
         POSITION   pos=m_ListResult.GetFirstSelectedItemPosition();
         CString content;
         CString employee;
         CString schedua;
         CString datetime;
         int nItem;
         if(pos!=NULL)  
         {  
              while(pos)  
              {   nItem=m_ListResult.GetNextSelectedItem(pos);
                   content=m_ListResult.GetItemText(nItem,0);
                   schedua=m_ListResult.GetItemText(nItem,1);
                   datetime=m_ListResult.GetItemText(nItem,2);
                   employee=m_ListResult.GetItemText(nItem,3);
              }
              GetDlgItem(IDC_EDIT4)->SetWindowText(content);
              GetDlgItem(IDC_EDIT5)->SetWindowText(schedua);
              GetDlgItem(IDC_EDIT7)->SetWindowText(datetime);
         }
         *pResult = 0;
     }
//ListCtrl控件双击事件
void CContentsSubmitDlg::OnNMDblclkList1(NMHDR *pNMHDRLRESULT *pResult)
     {
     //   CString s="您双击了选择项";
     //   AfxMessageBox(s);
         CString aa=(( CContentsSubmitApp *)AfxGetApp())->namelogin;
         aa.TrimLeft(" ");     
         aa.TrimRight("     ");
         aa.TrimRight(" ");
         aa.TrimRight(" ");
         aa.TrimRight("/t");
         POSITION   pos=m_ListResult.GetFirstSelectedItemPosition();
         CString content;
         CString employee;
          int nItem;
         if(pos!=NULL)  
         {  
               while(pos)  
               {    nItem=m_ListResult.GetNextSelectedItem(pos);
      content=m_ListResult.GetItemText(nItem,0); employee=m_ListResult.GetItemText(nItem,3);
               }
 if(employee!=aa)
     { AfxMessageBox("您不能删除别人的提报内容?",MB_OK);         return;            }
      else
      {   ADOconn m_conn;   _bstr_t vSQL="";
 CString s_Conn="Provider=SQLOLEDB;Server=10.128.128.221;Database=Eink;uid=stone;pwd=stone";
 vSQL="delete contens where workcontents='"+content+"' and employee='"+employee+"'";
         try
         { m_conn.OnInitADOConn(s_Conn);
          UINT YORN=AfxMessageBox("您确认删除该记录吗?",MB_YESNO);
          if(YORN==IDYES)
         {    m_conn.ExcuteSQL(vSQL);             }
         else {             return;               }
          }
          catch(...)
          {       AfxMessageBox("数据库删除错误",MB_OK);                 }
         AfxMessageBox("数据成功删除",MB_OK);
         m_ListResult.DeleteItem(nItem);
         }        }
         *pResult = 0;
}

************************************************************************************************************************************

//为设备环境句柄设置颜色
HBRUSH CContentsSubmitDlg::OnCtlColor(CDCpDCCWndpWndUINT nCtlColor)
     {
         HBRUSH hbr = CDialog::OnCtlColor(pDCpWndnCtlColor);
         int ctrid=pWnd->GetDlgCtrlID();
         if(ctrid==IDC_EDIT4)//则IDC_EDIT4的颜色为下面的颜色
              {            
                       pDC->SetTextColor(RGB(0,0,255));  
                       pDC->SetBkMode(OPAQUE); 
                       pDC->SetBkColor(RGB(255,255,255));
                       return   brushBlack;
               }  
         return hbr;
     }
 
//组合框选中事件
void CContentsSubmitDlg::OnCbnSelchangeCombo1()
     {
         int nsel1=m_belong.GetCurSel();
         switch(nsel1)
         {
         case 0 :
              m_ProjectName.ResetContent();
              m_ProjectName.AddString("数据抓取程序开发");
              break;
         case 1:
              m_ProjectName.ResetContent();
              m_ProjectName.AddString("网络架设");
              break;
         default:
              m_ProjectName.ResetContent();
              m_ProjectName.AddString("您没有选择团队");
         }
      }
//统计工作内容编辑框控件输入的行数(回车符表示换行),并将每行中以-号为分割符的内容写入到数据库中
void CContentsSubmitDlg::OnBnClickedButton1()
{    UpdateData(true);
CString workcontents,employees,scheduals,completedates,departments,teams,projects,
projecttimes,weeks;
         workcontents=this->m_workcontents;
         employees=this->m_employee;
         projecttimes=this->m_projecttime;
         GetDlgItem(IDC_EDIT1)->GetWindowText(m_vdepartment);
         departments=m_vdepartment;
         //****************处理工作内容
         CString strSrc =m_workcontents,strSrc1=m_workcontents;
         strSrc.TrimLeft(" ");     
         strSrc.TrimRight(" ");
         strSrc.TrimRight(" ");
         strSrc.TrimRight(" ");
         strSrc.TrimRight("/t");
         int countn=0;//统计工作内容的条数,以换行符号为标记
         int pos;///n的位置     int pos1;//-的位置
         int k;
         CString contents1[10];//考虑到每个人提报最多内容不会超过10条,该数组用来存储每一行        for(int j=0;;j++)
         {
              pos=strSrc.FindOneOf("/n");
              if(pos!=-1)
              {
                   countn++;
              }
              else
              {                  break;
              }
              contents1[j]=strSrc.Left(pos);//将值存储到该数组[]
              strSrc=strSrc.Right(strSrc.GetLength()-pos-1);
         }
         countn=countn+1;//条数=count+1
         CString contents[10];
         CString resultcontents[10][3];//用该2维数组存储每条中每项的值
         for(k=0;k<countn-1;k++)
         {
              pos=strSrc1.FindOneOf("/n");
              contents[k]=strSrc1.Left(pos);
              pos1=contents[k].FindOneOf("-");
              resultcontents[k][0]=contents[k].Left(pos1);
              contents[k]=contents[k].Right(contents[k].GetLength()-pos1-1);
              pos1=contents[k].FindOneOf("-");
              resultcontents[k][1]=contents[k].Left(pos1);
              contents[k]=contents[k].Right(contents[k].GetLength()-pos1-1);
              pos1=contents[k].FindOneOf("-");
              resultcontents[k][2]=contents[k];
              strSrc1=strSrc1.Right(strSrc1.GetLength()-pos-1);
         }
//专门处理最后一行
         pos1=strSrc1.FindOneOf("-");
         resultcontents[k][0]=strSrc1.Left(pos1);
         strSrc1=strSrc1.Right(strSrc1.GetLength()-pos1-1);
         pos1=strSrc1.FindOneOf("-");
         resultcontents[k][1]=strSrc1.Left(pos1);
         strSrc1=strSrc1.Right(strSrc1.GetLength()-pos1-1);
         pos1=strSrc1.FindOneOf("-");
         resultcontents[k][2]=strSrc1;
         int nsel=m_belong.GetCurSel();
         if(nsel==CB_ERR)
         {   
              AfxMessageBox("没有选团队名称");
         return;
         }
         m_belong.GetLBText(nsel,m_vbelong);
         int nsel1=m_week.GetCurSel();
         if(nsel1==CB_ERR)
         {
              AfxMessageBox("没有选周会梯次");
              return;
         }
         m_week.GetLBText(nsel1,m_vweek);
 
         int nsel2=m_ProjectName.GetCurSel();
         if(nsel2==CB_ERR)
         {
              AfxMessageBox("没有选项目名称");
              return;
         }
         m_ProjectName.GetLBText(nsel2,m_vprojectname);
          if((workcontents=="")||(this->m_employee=="")||(projecttimes==""))
         {
              AfxMessageBox("您所提报的信息不完整");
              return;
         }
         else
         {                          
ADOconn m_conn;             _bstr_t vSQL="";
CString s_Conn="Provider=SQLOLEDB;Server=10.128.128.221;Database=Eink;uid=stone;pwd=stone";
for(int l=0;l<countn;l++)//将每行分割后写入到数据库中
{
vSQL="insert into contens(department,week,team,project,employee,projecttime,workcontents,
schedule,completedate) values('"+departments+"','"+m_vweek+"','"+m_vbelong+"','"
+m_vprojectname+"','"+employees+"','"+projecttimes+"','"+resultcontents[l][0]+"','"
+resultcontents[l][1]+"','"+resultcontents[l][2]+"')";
try
{m_conn.OnInitADOConn(s_Conn);            m_conn.ExcuteSQL(vSQL);              }
catch(...)
{    AfxMessageBox("数据库写入错误",MB_OK);                  }
}
m_conn.ExitConnect();
AfxMessageBox("补充周报内容成功",MB_OK);
}
}

************************************************************************************************************************************

//判断数据库中是否存在该记录
ADOconn m_conn;    _bstr_t vSQL="";_variant_t vResult[3]; _RecordsetPtr m_pRecordset;
CString s_Conn="Provider=SQLOLEDB;Server=10.128.128.221;Database=Eink;uid=stone;pwd=stone";
vSQL="select * from contens where employee='"+employees+"' and week='"+m_vweek+"'";
m_conn.OnInitADOConn(s_Conn);
m_pRecordset=m_conn.GetRecordSet(vSQL);
if(!m_pRecordset->ADOEOF)
AfxMessageBox("您已经提报了,如果您还想补充你的周会内容,请选择补充周会内容按钮",MB_OK); }
else
{//做你想做的事情}
//在A对话框前弹出一B对话框
Login dlog;//B对话框的对象
if(dlog.DoModal()!=IDOK)
{        return false; }
CContentsSubmitDlg dlg;//A对话框对象
m_pMainWnd = &dlg;
//需要密码的登陆框
void Login::OnBnClickedOk()
{    UpdateData(true);
    if(this->m_User=="" || this->m_Password=="")
     {        AfxMessageBox("用户名和密码不能为空",MB_OK);       return;
     }
     else
     {   
ADOconn m_conn;    _bstr_t vSQL="";_variant_t vResult; _RecordsetPtr m_pRecordset;
CString s_Conn="Provider=SQLOLEDB;Server=10.128.128.221;Database=Eink;uid=stone;pwd=stone";
vSQL="select employee_name from employee where employee_id='"+m_User+"'and password='"+m_Password+"'";
m_conn.OnInitADOConn(s_Conn);    m_pRecordset=m_conn.GetRecordSet(vSQL);
     if(m_pRecordset->ADOEOF)
         {    AfxMessageBox("您的用户名密码输入错误",MB_OK);          return;       }
         else
         {    vResult=m_pRecordset->GetCollect(_variant_t((long)0));
              employeelogin_name=(LPCTSTR)(_bstr_t)vResult;
              (( CContentsSubmitApp *)AfxGetApp())->namelogin=employeelogin_name;  
              //通过全局变量保存用户名
         }
        OnOK();
     }
}

************************************************************************************************************************************

//获取系统当前时间
COleDateTime timeNow;
     timeNow = COleDateTime::GetCurrentTime();
     int year = timeNow.GetYear();
     int month = timeNow.GetMonth();
     int day = timeNow.GetDay();
     CString cyear,cmoth,cday;
     cyear.Format("%d",year);
     cmoth.Format("%d",month);
     cday.Format("%d",day);
     CString datenow=cyear+"年"+cmoth+"月"+cday+"日";
     GetDlgItem(IDC_EDIT9)->SetWindowText(datenow);
 
 
//全局变量的使用
在common.cpp中
#include "stdafx.h"
#include "Common.h"
之后定义如下全局变量:
// Mutex对象的名称
char g_strRName[64] = "RedHorse";
char g_strGName[64] = "GreenHorse";
char g_strBName[64] = "BlueHorse";
 
// Mutex对象的句柄
HANDLE g_hRMutex;
HANDLE g_hGMutex;
HANDLE g_hBMutex;
在Dlg.cpp中要用到这些全局变量,
则在#include “”之后声明如下:
extern char g_strRName[64];
extern char g_strGName[64];
extern char g_strBName[64];
 
extern HANDLE g_hRMutex;
extern HANDLE g_hGMutex;
extern HANDLE g_hBMutex;
//另一种将数据写入到数据库的方式
connstr="Provider=SQLOLEDB;Server=10.144.0.126;Database=CanaryData;uid=testdata;pwd=testdata";                           
m_AdoConnNew.OnInitADOConn(connstr);                   
vSQL1="Canary_All_Small";                     
m_pRecordset1=m_AdoConnNew.GetRecordSet(vSQL1,connstr);
if(!m_pRecordset1->Supports(adAddNew))
{
     AfxMessageBox("10.144.0.126 DBServer, 数据不能被写入数据表(Canary_All_Small)",MB_OK,0);      return;
}
m_pRecordset1->AddNew();        
m_pRecordset1->Fields->GetItem(_variant_t("TestStation_Type"))->Value=_bstr_t(gatwickcamera_temp[3]);
m_pRecordset1->Fields->GetItem(_variant_t("TestStation_NO"))->Value=_bstr_t(gatwickcamera_temp[4]);   
m_pRecordset1->Update();
设置对话框的具体步骤:   
  1 给你的工程中的对话框类添加一个CBrush变量,如:   
  CBrush   m_bkBrush;         //准备一把背景刷子   
  2 在对话框的初始化函数OnInitDialog中return   TRUE的前面添加一行代码:   
  m_bkBrush.CreateSolidBrush(RGB(255,255,0));           //创建一把黄色的背景刷子   
  3 最后把你原来的代码改成如下:   
  HBRUSH   CEX06aDialog::OnCtlColor(CDC*   pDC,   CWnd*   pWnd,   UINT   nCtlColor)   
  {   
  HBRUSH   hbr   =   CDialog::OnCtlColor(pDC,   pWnd,   nCtlColor);   
    
  //   TODO:     在此更改   DC   的任何属性   
  if(nCtlColor==CTLCOLOR_DLG)       //如果是CTLCOLOR_EDIT   edit背景色能改变,为什么改为   
                                                                                //edit   edit   box背景色改不了   
                            return   m_bkBrush;           //返回刚才创建的背景刷子   
    
                    //   TODO:     如果默认的不是所需画笔,则返回另一个画笔   
  return   hbr;   
  }  
//获取Date time picke控件的值转化为字符串
       CTime ct;
       m_sumbmitDate.GetTime(ct);
       int year=ct.GetYear();
       int month=ct.GetMonth();
       int day=ct.GetDay();
       CString ay,am,ad;
       ay.Format("%d",year);
       am.Format("%d",month);
       ad.Format("%d",day);
       CString submitdate=ay+"年"+am+"月"+ad+"日";
//Tab Contrl控件的使用
TC_ITEM *m_pTCItem;
     m_pTCItem=new TC_ITEM;
     m_pTCItem->mask=TCIF_TEXT;
     m_pTCItem->pszText=".net 2003开发指南";
     m_Preview_TabCtrl.InsertItem(1,m_pTCItem);
     m_pTCItem->pszText=".net 2005开发指南";
     m_Preview_TabCtrl.InsertItem(2,m_pTCItem);
    
************************************************************************************************************************************

C++常见文件操作示例
1.       复制文件:
    UpdateData();
     //提示用户是否复制文件
     if (MessageBox("是否将原始文件复制到目标文件?","提示",MB_OKCANCEL)==IDOK)
     {    CFile *pSrcFile=NULLCFile *pDstFile=NULL;//定义两个指向原始文件和目标文件的指针
         TRY
         {    pSrcFile=new CFile(m_szSrcFileCFile::modeRead); //原始文件赋值给指针
              pDstFile=new CFile(m_szDrcFileCFile::modeCreate|CFile::modeWrite);//目标文件           int nRead;    //读取的字节数
              char szBuffer[1024];   //复制缓冲区,用于将读取的数据缓存,然后写入
              //循环直到读取的字节数为0
             while (nRead=pSrcFile->Read(szBuffer,sizeof(szBuffer)))
            {       pDstFile->Write(szBuffer,nRead);            }
              pSrcFile->Close();          pDstFile->Close();//关闭文件指针
              delete pSrcFile;            delete pDstFile;//删除,否则内存泄漏
              MessageBox("文件复制成功。","提示",MB_OK); //提示复制成功
         }
         CATCH(CFileException,e)
         {   MessageBox("文件复制失败。","提示",MB_OK); //出错,提示复制失败
              if (pSrcFile!=NULL)
              {    pSrcFile->Abort(); delete pSrcFile; //安全关闭原始文件
              }
              if (pDstFile!=NULL)
              {    pDstFile->Abort(); delete pDstFile;
              }
         }
         END_CATCH
     }   
2.       剪切文件内容(从A文件把内容剪切到B文件,并删除A文件,AB两文件类型相同)
     UpdateData();
     //提示用户是否移动文件
     if (MessageBox("是否将原始文件移动到目标文件?","提示",MB_OKCANCEL)==IDOK)
     {    CFile *pSrcFile=NULL;       CFile *pDstFile=NULL;
         TRY
         {    pSrcFile=new CFile(m_szSrcFileCFile::modeRead); //原始文件
              pDstFile=new CFile(m_szDrcFileCFile::modeCreate|CFile::modeWrite);//目标文件
              int nRead;    //读取的字节数
              char szBuffer[1024];   //复制缓冲区,用于将读取的数据缓存,然后写入
              //循环直到读取的字节数为0
              while (nRead=pSrcFile->Read(szBuffer,sizeof(szBuffer)))
              {             pDstFile->Write(szBuffer,nRead);
              }
         pSrcFile->Close();          pDstFile->Close();
              delete pSrcFile;            delete pDstFile;
              CFile::Remove(m_szSrcFile); //删除原文件
              MessageBox("文件移动成功。","提示",MB_OK); //提示移动成功
         }
         CATCH(CFileException,e)
         {    MessageBox("文件移动失败。","提示",MB_OK); //出错,提示移动失败
              if (pSrcFile!=NULL)
              {    pSrcFile->Abort();               delete pSrcFile;
              }
              if (pDstFile!=NULL)
              {    pDstFile->Abort();               delete pDstFile;
              }
         }
         END_CATCH
     }
3.       删除文件(CFile::Remove(m_szSrcFile)见上例)
4.       创建文件
TRY
     {    //creatfilename.txt为所要创建的文件
CFile file=new CFile("creatfilename.txt",CFile::modeCreate|CFile::modeWrite);
         AfxMessageBox("creatfilename.txt文件创建成功",MB_OK);
     }
     CATCH(CFileException,e)
     {        TRACE("Error=%u",e->m_cause);    }
     END_CATCH
     }
5.       读取文件
     iniDir=strPath;//文件路径:如C:D/test.txt
     CStdioFile iniConfigFile;
     if(iniConfigFile.m_pStream=fopen(iniDir,"r+w"))//打开文件
     {    int pass[3]={0};//每班合格人数       int total[3]={0};//每班总人数
         while(!feof(iniConfigFile.m_pStream))//判断文件是否是末尾
         {    char buf[1024];//定义缓冲数组存储读取的值
              LPTSTR temp=iniConfigFile.ReadString(buf,1024);//读第一行并将值存储到缓冲数组
              CString strSrc = temp;//将指向第一行的指针赋值给strSrc
              //去掉该行的左右两端空格,回车符,跳格符
              strSrc.TrimLeft(" ");           strSrc.TrimRight(" ");
              strSrc.TrimRight(" ");           strSrc.TrimRight(" ");
              strSrc.TrimRight("/t");          strSrc.TrimRight("/n ");
              int pos;//该行分隔符的位置
              //可以用for语句改写
              CString studentInfo[5];//用来存储第一行的以逗号做为分隔符的值
              for(int i=0;i<4;i++)
              {    pos=strSrc.FindOneOf(",");
                   studentInfo[i]=strSrc.Left(pos);
                   strSrc=strSrc.Right(strSrc.GetLength()-pos-1);
              }
              studentInfo[4]=strSrc;
//以下是对读取到的数据进行处理,好写在数据库中,不是本处的重点,详细代码,参考DataTODataBase的源码
//以下三行代码是将CString类型转换为整型的代码
                   char * pchar2=studentInfo[4].GetBuffer(studentInfo[4].GetLength());
                   int iscore=atoi(pchar2);
                   if(iscore>=60) pass[0]++;
              }
     }
else
     {
         CString err;
         err.Format("找不到文件:%S /n",iniDir);
         AfxMessageBox(err,MB_ICONSTOP);
     }
     iniConfigFile.Close();
     //为了避免重复转换最好导入后将原始数据删除
    remove(iniDir);
6.       写文件
     CString classid[3]={"class1","class2","class3"};
         float yield[3]={0.0};//班级合格率
         for(int i=0;i<3;i++)
         {    yield[i]=float(pass[i])/float(total[i]);
              WriteTotalToDataBase(classid[i],total[i],pass[i],yield[i]);
//该函数是将每个班的总信息写入到classTotal表中
         }
         //用C语言写入到classTotal.txt中,
         string filename="classTotal.txt";
         FILE * fh;
         fh = fopen(filename.c_str(), "wb");
         if(fh == NULL) {   AfxMessageBox("被写入的文件打开失败",MB_OK);   }
         CString total_str[3],pass_str[3],yield_str[3];
         for(int i=0;i<3;i++)
         {    //以下三句是把int型转化为CString型
total_str[i].Format("%d",total[i]);       pass_str[i].Format("%d",pass[i]);
              yield_str[i].Format("%f",yield[i]);
         }
        for(int i=0;i<3;i++)
         {//定义以个string类型用来连接以上信息值
string filecontents=classid[i] + "," +total_str[i] + "," +pass_str[i] + "," +yield_str[i]+ "/t";
         fprintf(fh,filecontents.c_str());//将信息写入fh
         }
          AfxMessageBox("数据成功写入classTotal.txt",MB_OK);
         if(fclose(fh) != 0)
         {        AfxMessageBox("被写入的文件关闭失败",MB_OK);       }
       //用C++语言写入到classTotal1.txt中
         CStdioFile mFile;
         CFileException mExcept;
         mFile.Open( "classTotal1.txt", CFile::modeWrite, &mExcept);
         CString filecontents1;
         for(int i=0;i<3;i++)
         {
      filecontents1=classid[i] + "," +total_str[i] + "," +pass_str[i] + "," +yield_str[i]+ "/n";
             mFile.WriteString(filecontents1);
         }
          AfxMessageBox("数据成功写入classTotal1.txt",MB_OK);
          mFile.Close();
7.       待续……..

************************************************************************************************************************************
C++常见类型转换示例
1.IP 控件的IP值转化为CString类型
CIPAddressCtrl    *c=(CIPAddressCtrl *)(GetDlgItem(IDC_IPADDRESS1));
     c->GetAddress(m_bIPAddress[0],m_bIPAddress[1],m_bIPAddress[2],m_bIPAddress[3]);
// m_bIPAddress[0]为BYTE类型,需要在类中定义public
     FileServerIP1.Format("%d",(int)m_bIPAddress[0]);
     FileServerIP2.Format("%d",(int)m_bIPAddress[1]);
     FileServerIP3.Format("%d",(int)m_bIPAddress[2]);
     FileServerIP4.Format("%d",(int)m_bIPAddress[3]);
     FileServerIP=FileServerIP1+"."+FileServerIP2+"."+FileServerIP3+"."+FileServerIP4;
2. CString类型转换为float,int,double类型
CString strval;
strval="12.43aa";
char* pChar1=strval.GetBuffer(strval.GetLength());
float fval=atof(pChar1);
double dval=atof(pChar1);
int ival=atoi(pChar1);
3. float,int,double类型转换为CString类型
CString total_str[3],pass_str[3],yield_str[3];
for(int i=0;i<3;i++)
total_str[i].Format("%d",total[i]);
     pass_str[i].Format("%d",pass[i]);
     yield_str[i].Format("%f",yield[i]);
}
4. string类型转化为double,int,char类型
       string strvar="3.1415926aa";
       double dvar=atof(strvar.c_str());
       cout<<"convert string to double "<<dvar<<endl;
       string strvar="2007a";
       int ivar=atoi(strvar.c_str());
       cout<<"convert string to int "<<ivar<<endl;
       string strvar="hello";
    const char* cvar=strvar.c_str();//去掉const会报错
       //const char* cvar=strvar.data();//去掉const会报错,两句一样的效果,本质呢?
       cout<<"convert string to char strvar="<<strvar<<" and cvar=";
    for(int i=0;i<strvar.length();i++)
              cout<<cvar[i];
    cout<<endl;
      
 5.int,double类型转换为string类型
       char buffer[1];
//需要个字符数组来存储写成: char buffer;char buffer[]都会出错?why
       int ivar=2007;
       string strvar=string(itoa(ivar, buffer, 10));
       cout<<"convert int to string "<<strvar<<endl;*/
    char buffer[352];
       double dvar=3.1415926;
       string strvar=string(gcvt(dvar, 5, buffer));
//中间数字表示精度,表示除去小数点的总共是五位,比如换成5.则结果为3.1416
       cout<<"convert double to string "<<strvar<<endl;
6.待续```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值