根據csv文件數據內容繪圖。
csv文件內容包括:圖形類型(橫線,豎線,橫半圓弧,豎半圓弧),長度(線長度,半圓半徑)。根據csv文件中提供的數據,在dialog中繪製出相應的圖形。如果要繪製的圖形超出dialog的
x軸邊界,則從x=0,y不變的座標開始繪製該圖形;如果超出了y軸邊界,則從x不變,y=0座標開始繪製。(編碼要求:從csv文件讀取的內容和操作使用鏈表類保持)。
例如:csv文件內容爲:(假設:a:橫線,b:豎線,c:橫半圓,d:豎半圓)
style,length
a, 50
b,50
c, 25
d, 25
首先要定義頭文件:
#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <vector>
#include <stdio.h>
using namespace std;
vector<string> str_iterator ; //to deposit the data
在初始化裏也可以加上如下語句:
m_fileName="d:\\recordset.csv";
UpdateData(FALSE);
然後在dialog中添加一個讀取文件的按鈕,並添加如下代碼:
UpdateWindow();
str_iterator.clear();
fstream istrm; //define a I/O stream
string s;
int pos,i;
char *store;
string name;
name=m_fileName;
UpdateData(TRUE);
store=(char *)name.c_str();
istrm.open(store,ios::in); //open the file by only-read
if(!istrm)
{
MessageBox("Can't open file!\n");
}
else
{
while(!istrm.eof())
{
istrm>>s;
i=0;
int log=1;
while(log)
{
pos = s.find(",",i);
if(pos == string::npos)
{ //if can't find
str_iterator .push_back(s.substr(i));
log=0;
}
else //if find the character of ","
str_iterator .push_back(s.substr(i,pos-i));
i = pos+1;
}
}
str_iterator.pop_back();
istrm.close();
UpdateWindow(); //引用"OnPaint()"
}
最後在"OnPaint()"裏面添加如下的處理代碼:
UpdateWindow();
CClientDC dc(this);
CPen pen(PS_SOLID,1,RGB(0,0,255));
CRect rect;
GetClientRect(&rect);
dc.MoveTo(5,46);
CPoint p;
int var;
char *ch;
CWnd *pWnd = GetDlgItem(IDC_STATIC);
CPen *pOldPen= dc.SelectObject(&pen);
int x=0;
while (x < str_iterator .size())
{
ch = (char*)str_iterator [x].c_str();
var = atoi((char*)str_iterator [x+1].c_str());
switch(*ch)
{
case 'a': // draw the horizontal line
{
p=dc.GetCurrentPosition();
if((p.x+var) > rect.right) // 判斷是否越界
{
dc.MoveTo(5,p.y);
}
p=dc.GetCurrentPosition();
dc.LineTo(p.x+var,p.y);
break;
}
case 'b': // draw the vertical line
{
p=dc.GetCurrentPosition();
if((p.y+var) > rect.bottom) // 判斷是否越界
{
dc.MoveTo(p.x,46);
}
p=dc.GetCurrentPosition();
dc.LineTo(p.x,p.y+var);
break;
}
case 'c': // draw the semicircle
{
p=dc.GetCurrentPosition();
if(((p.x+var*2) > rect.right)) // 判斷是否越界
{
dc.MoveTo(5,p.y);
}
if (((p.y+var) > rect.bottom))
{
dc.MoveTo(p.x,46);
}
p=dc.GetCurrentPosition();
dc.ArcTo(p.x,p.y-var,(p.x+var*2),p.y+var,p.x,p.y,(p.x+var*2),p.y);
break;
}
case 'd': // draw the semicircle
{
p=dc.GetCurrentPosition();
if((p.x+var)> rect.right) // 判斷是否越界
{
dc.MoveTo(5,p.y);
}
if((p.y+var*2)>rect.bottom)
{
dc.MoveTo(p.x,46);
}
p=dc.GetCurrentPosition();
dc.Arc(p.x-var,(p.y+var*2),p.x+var,p.y,p.x,(p.y+var*2),p.x,p.y);
dc.MoveTo(p.x,p.y+var*2);
break;
}
default:
break;
}
x = x+2;
}
dc.SelectObject(pOldPen);