Show toolbar

2013年7月18日 星期四

Data Synchronization Update

標題:同步變更數據
Node.JS (getdata.js):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
var server,
ip = "127.0.0.1",
port = 1337,
http = require("http"),
url = require("url"),
fs = require("fs"),
qs = require("querystring");
var textPath = "p.txt";
server = http.createServer(function (req, res) {
var polling = {
timeover : false,
timeout : null,
request : function(q) {
this.timeout = setTimeout(function() {
polling.timeover = true;
}, 10000);
this.action(q);
},
action : function(q) {
if(this.timeover == true) { //確認連線逾時
q.callback({});
} else {
fs.readFile(textPath, "utf-8", function(err, file) {
if(q.json.lastTime < qs.parse(file).lastTime) { //有新資料
q.callback(qs.parse(file));
} else { //駐列輪巡
setTimeout(function() { polling.action(q) }, 100);
}
});
}
}
};
switch(url.parse(req.url).pathname) {
case "/jquery":
fs.readFile("js/jquery-1.9.1.js", function (err, data) {
if(err) throw err;
res.writeHead(200, {"Content-Type": "text/javascript", "Content-Length":data.length});
res.write(data);
res.end();
});
break;
case "/index":
fs.readFile("index.html", function (err, data) {
if(err) throw err;
res.writeHead(200, {"Content-Type": "text/html", "Content-Length":data.length});
res.write(data);
res.end();
});
break;
case "/sendData":
var sendData = "";
var lastTime = new Date().getTime();
req.setEncoding("utf8");
req.addListener("data", function(sendDataChunk) {
sendData += sendDataChunk;
});
req.addListener("end", function() {
sendData += "&lastTime=" + lastTime;
fs.open(textPath, "w", 0644, function(err, fd) {
if(err) throw err;
fs.write(fd, sendData, 0, "utf8", function(err) {
if(err) throw err;
fs.closeSync(fd);
var json = JSON.stringify({lastTime: lastTime});
res.writeHead(200, {
"Content-Type": "text/json",
"Content-Length": json.length
});
console.log(json);
res.end(json);
})
});
});
break;
case "/getData":
var getData = "";
req.setEncoding("utf8");
req.addListener("data", function(getDataChunk) {
getData += getDataChunk;
});
req.addListener("end", function() {
polling.request({
json : qs.parse(getData),
callback : function(data) {
var json = JSON.stringify(data);
res.writeHead(200, {
"Content-Type": "text/json",
"Content-Length": json.length
});
res.end(json);
}
});
});
break;
default:
res.writeHead(200, {"Content-Type": "text/html"});
res.write("Page not found.");
res.end();
break;
}
});
server.listen(port);
console.log("Server running at http://" + ip + ":" + port);
HTML (index.html):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-TW" xml:lang="zh-TW">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
<script src="/jquery"></script>
<script type="text/javascript">
$(function() {
var localurl = window.location.protocol + "//" + window.location.host;
var lastTime = 0;
$("#sendBtn").click(function() {
var username = $("#username").val();
var xValue = $("#xValue").val();
var yValue = $("#yValue").val();
var zValue = $("#zValue").val();
$.post("/sendData", {user: username, x: xValue, y: yValue, z: zValue},
function(data) {
console.log("Message Send on " + data.lastTime);
}, "json");
});
var pollingData = function() {
$.ajax({
cache: false,
dataType: "json",
type: "POST",
url: localurl + "/getData",
data: {lastTime: lastTime},
error: function (xhr, status, error) {
document.write("Error");
},
success: function (json) {
//console.log(json);
if(!$.isEmptyObject(json)) { //判斷內容是否為空
console.log("Update...");
//lastTime = new Date().getTime();
$("#username").val(json.user);
$("#xValue").val(json.x);
$("#yValue").val(json.y);
$("#zValue").val(json.z);
lastTime = json.lastTime;
pollingData();
} else { //繼續輪巡
console.log("Pulling...");
pollingData();
}
}
});
};
pollingData();
});
</script>
</head>
<body>
name: <input type="text" id="username" value="QQBoxy" /><br />
x: <input type="text" id="xValue" value="3" /><br />
y: <input type="text" id="yValue" value="4" /><br />
z: <input type="text" id="zValue" value="5" /><br />
<button id="sendBtn">Send</button>
</body>
</html>
Batch (Start.bat):

說明:
使用Node.JS與jQuery進行數據同步變更。

Read STL Model file and export graphics using GD Library

標題:讀取STL模型檔案並使用GD Library匯出圖形
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#include "stdafx.h"
#include <iostream>
#include <regex>
#include <fstream>
#include "gd/gd.h"
#include "gd/gdfontg.h"
#include "gd/gdfontt.h"
#include "gd/gdfonts.h"
#include "gd/gdfontmb.h"
#include "gd/gdfontl.h"
#pragma comment(lib, "lib/bgd.lib")
using namespace std;
class pos
{
public:
float x;
float y;
float z;
};
class ERR
{
private:
int kind;
public:
ERR(int k) : kind(k){}; //建構函式
char* message()
{
switch(kind)
{
case 0:
return "Parameter Error!";
case 1:
return "Path Error!";
case 2:
return "File Error!";
case 3:
return "Array Size is too small.";
case 4:
return "STL Format Error!";
}
}
};
void draw(gdImagePtr im, pos vArr[], int v, int color)
{
int i = 0;
for(i=0;i<v;i+=3)
{
gdImageLine(im, (int)vArr[i].x, (int)vArr[i].y, (int)vArr[i+1].x, (int)vArr[i+1].y, color);
gdImageLine(im, (int)vArr[i+1].x, (int)vArr[i+1].y, (int)vArr[i+2].x, (int)vArr[i+2].y, color);
gdImageLine(im, (int)vArr[i].x, (int)vArr[i].y, (int)vArr[i+2].x, (int)vArr[i+2].y, color);
}
}
int main(int argc, char* argv[])
{
const float zoom = 5;
const int arrSize = 3000;
const int width = 500;
const int height = 500;
int i = 0, normals = 0, vertexs = 0;
char pathChar[1024];
char stlName[1024];
string lines = "";
pos *normalArr;
pos *vertexArr;
regex pathRegex("([a-zA-Z]\:\\\\(?:[^\\\\]+\\\\)*)(.*)"); //"C:\\temp\\hello.txt"
regex solid(" *solid.*");
regex facetNormal(" *facet normal ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?)");
regex outerLoop(" *outer loop");
regex vertex(" *vertex ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?)");
regex endLoop(" *endloop");
regex endfacet(" *endfacet");
regex endsolid(" *endsolid");
cmatch pathMatch;
smatch normalMatch;
smatch vertexMatch;
try
{
if(argc<2) throw ERR(1); //Check Parameter
strcpy(pathChar, argv[1]); //Get STL Path
if(!regex_match(pathChar, pathMatch, pathRegex)) throw ERR(1); //Check STL Path
strcpy(stlName, pathMatch[2].str().c_str()); //Get STL Name
ifstream File(pathChar);
if (!File.is_open()) throw ERR(2); //Check File
normalArr = new pos[arrSize]; //宣告Facet normal動態陣列大小
vertexArr = new pos[arrSize*3]; //宣告Vertex動態陣列大小
cout << "Reading Now..." << endl;
//solid
if(!File.good()) throw ERR(4);
getline(File, lines);
if(!regex_match(lines, solid)) throw ERR(4);
while(File.good())
{
if(normals >= arrSize) throw ERR(3); //Check Array Size
//facet normal
getline(File, lines);
if(regex_match(lines, normalMatch, facetNormal))
{
normalArr[normals].x = atof(normalMatch[1].str().c_str()) + width/2;
normalArr[normals].y = atof(normalMatch[2].str().c_str()) + height/2;
normalArr[normals].z = atof(normalMatch[3].str().c_str());
normals++;
}
else if(regex_match(lines, endsolid)) //end solid
{
break;
}
else
{
throw ERR(4);
}
//outer loop
getline(File, lines);
if(!regex_match(lines, outerLoop)) throw ERR(4);
//vertex
for(i=0;i<3;i++)
{
getline(File, lines);
if(regex_match(lines, vertexMatch, vertex))
{
vertexArr[vertexs].x = atof(vertexMatch[1].str().c_str())*zoom + width/2;
vertexArr[vertexs].y = atof(vertexMatch[2].str().c_str())*zoom + height/2;
vertexArr[vertexs].z = atof(vertexMatch[3].str().c_str())*zoom;
vertexs++;
}
else
{
throw ERR(4);
}
}
//end loop
getline(File, lines);
if(!regex_match(lines, endLoop)) throw ERR(4);
//end facet
getline(File, lines);
if(!regex_match(lines, endfacet)) throw ERR(4);
}
File.close();
cout << "Facet Normal: " << normals << endl;
cout << "Vertex: " << vertexs << endl;
cout << "Done." << endl;
// --- draw ---
cout << "Drawing Now..." << endl;
FILE *out;
int size;
char *data;
gdImagePtr im = gdImageCreate(width, height);
int white = gdImageColorAllocate(im, 255, 255, 255), //Background
black = gdImageColorAllocate(im, 0, 0, 0),
blue = gdImageColorAllocate(im, 0, 0, 255),
cyan = gdImageColorAllocate(im, 0, 255, 255),
green = gdImageColorAllocate(im, 128, 255, 0),
red = gdImageColorAllocate(im, 255, 0, 0),
purple = gdImageColorAllocate(im, 255, 0, 255),
orange = gdImageColorAllocate(im, 255, 128, 0),
yellow = gdImageColorAllocate(im, 255, 255, 0);
strcpy(pathChar, argv[0]); //Get Execution Path
if(!regex_match(pathChar, pathMatch, pathRegex)) throw ERR(1); //Check Execution Path
strcpy(pathChar, pathMatch[1].str().c_str()); //Get Folder Path
strcat(pathChar, stlName); //Connections Folder Path and STL Name
strcat(pathChar, ".png"); //Connections Path and Extension
out = fopen(pathChar, "wb");
if (!out) throw ERR(1);
draw(im, vertexArr, vertexs, black);
data = (char *) gdImagePngPtr(im, &size);
if (!data) throw ERR(2);
if (fwrite(data, 1, size, out) != size) throw ERR(3);
if (fclose(out) != 0) throw ERR(4);
gdFree(data);
cout << "Done." << endl;
}
catch(ERR e)
{
cout << e.message() << endl;
}
system("pause");
return 0;
}

說明:
首先拖曳一個STL模型檔案至執行檔以進行讀取,一邊進行檔案比對一邊將點資料存入類別陣列內,再使用GD Library匯出png圖片檔。

Solving Matrix Inverse using Pointer

標題:使用指標求解n維矩陣
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <iomanip>
using namespace std;
void print(double *Arr, int m)
{
int i = 0, j = 0;
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
cout << *(Arr+i*m+j) << setprecision(2) << "\t";
}
cout << endl;
}
}
void printInverse(double *Matrix, double *Inverse, int m)
{
int i = 0, j = 0;
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
cout << *(Matrix+i*m+j) << setprecision(2) << "\t";
}
cout << "|\t";
for(j=0;j<m;j++)
{
cout << *(Inverse+i*m+j) << setprecision(2) << "\t";
}
cout << endl;
}
}
void readfile(string filePath, double *Matrix)
{
int m = 0, n = 0, i = 0;
string lines = "";
string::const_iterator start;
match_results<string::const_iterator> matchMatrix; //迭代器
regex regMatrix("([0-9]+)+");
ifstream outputFile(filePath);
if (outputFile.is_open()) //Check File
{
while(outputFile.good())
{
getline(outputFile, lines);
start = lines.begin();
while (regex_search(start, lines.cend(), matchMatrix, regMatrix))
{
*(Matrix+i) = atof(matchMatrix[1].str().c_str());
i++;
start = matchMatrix[0].second;
}
m++;
}
outputFile.close();
}
}
double plusnum(double num)
{
if(num < 0) return -1 * num;
return num;
}
void rowSwap(double *Matrix, int ma, int mb, int m)
{
int i = 0;
double *Temp = new double[m];
for(i=0;i<m;i++)
{
*(Temp+i) = *(Matrix+ma*m+i);
*(Matrix+ma*m+i) = *(Matrix+mb*m+i);
*(Matrix+mb*m+i) = *(Temp+i);
}
}
void inverse(double *Matrix, double *Inverse, int m)
{
int i = 0, j = 0, k = 0;
double temp = 0;
//*(Matrix + rows * m + columns) 看成 Matrix[rows][columns]
for(int i=0; i<m; i++)
{
for(int j=i+1; j<m; j++)
{
if(plusnum(*(Matrix + j * m + i)) > plusnum(*(Matrix + i * m + i)))
{
rowSwap(Matrix, i, j, m); // 互換Matrix矩陣兩行
rowSwap(Inverse, i, j, m); // 互換Inverse矩陣兩行
//cout << "[" << i << "][" << j << "]Swap:" << endl;
//printInverse(Matrix, Inverse, m);
}
}
// 消去
for(int j=0; j<m; j++) //第 i 次消去運算,以第 i 行作為主要行,將其上下各行的第 i 列元素化為零
{
if(j != i)
{
// 進行消去運算,將第 i 列上下方的元素化為零
double temp = *(Matrix + j * m + i) / *(Matrix + i * m + i);
// 注意此處 k 可從 i+1 開始
//for(int k=i+1; k<m; k++)
for(int k=0; k<m; k++)
{
*(Matrix + j * m + k) -= (*(Matrix + i * m + k) * temp);
}
// 注意此處 k 要從 0 開始
for(int k=0; k<m; k++)
{
*(Inverse + j * m + k) -= (*(Inverse + i * m + k) * temp);
}
//cout << "[" << i << "][" << j << "]Matrix:" << endl;
//printInverse(Matrix, Inverse, m);
}
}
}
// Matrix 已經是對角矩陣,只要在將其對角線元素化為 1 即可
// 此時僅需對 Inverse 矩陣作運算
//cout << "[" << i << "][" << j << "]Inverse:" << endl;
//printInverse(Matrix, Inverse, m);
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
*(Inverse + i * m + j) /= *(Matrix + i * m + i);
}
//cout << "[" << i << "][" << j << "]Inverse:" << endl;
//printInverse(Matrix, Inverse, m);
}
}
int main(int argc, char *argv[])
{
const int m = 4;
int i = 0, j = 0;
double Matrix[m][m] = {};
double Inverse[m][m] = {};
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
if(i == j)
Inverse[i][j] = 1;
else
Inverse[i][j] = 0;
}
}
readfile("matrix.txt", &Matrix[0][0]);
cout << "Matrix:" << endl;
print(&Matrix[0][0], m);
inverse(&Matrix[0][0], &Inverse[0][0], m);
cout << endl;
cout << "Inverse:" << endl;
print(&Inverse[0][0], m);
system("pause");
return 0;
}
TEXT (matrix.txt):

說明:
先讀取矩陣數據再利用指標的方式求得n維度反矩陣的解。

2013年7月16日 星期二

Check the ASCII format of STL file

標題:檢查ASCII STL格式範例
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <regex> //string lib here
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0, num = 1;
const char *filePath = "TriangleASCII.STL";
string lines = "";
regex solid(" *solid.*");
regex facetNormal(" *facet normal .+ .+ .+");
regex outerLoop(" *outer loop");
regex vertex(" *vertex .+ .+ .+");
regex endLoop(" *endloop");
regex endfacet(" *endfacet");
regex endsolid(" *endsolid");
//regex number("[+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?");
ifstream outputFile(filePath);
if (outputFile.is_open()) //Check File
{
num++;
//solid
if(outputFile.good())
{
getline(outputFile, lines);
if(regex_match(lines, solid))
{
cout << lines << endl;
while(outputFile.good())
{
//facet normal
getline(outputFile, lines);
if(regex_match(lines, facetNormal))
{
cout << lines << endl;
num++;
} else if(regex_match(lines, endsolid)) { //end solid
cout << lines << endl;
cout << "Done." << endl;
break;
} else {
cout << "[line " << num << " format error] " << lines << endl;
break;
}
//outer loop
getline(outputFile, lines);
if(regex_match(lines, outerLoop))
{
cout << lines << endl;
num++;
} else {
cout << "[line " << num << " format error] " << lines << endl;
break;
}
//vertex
getline(outputFile, lines);
if(regex_match(lines, vertex))
{
cout << lines << endl;
num++;
} else {
cout << "[line " << num << " format error] " << lines << endl;
break;
}
getline(outputFile, lines);
if(regex_match(lines, vertex))
{
cout << lines << endl;
num++;
} else {
cout << "[line " << num << " format error] " << lines << endl;
break;
}
getline(outputFile, lines);
if(regex_match(lines, vertex))
{
cout << lines << endl;
num++;
} else {
cout << "[line " << num << " format error] " << lines << endl;
break;
}
//end loop
getline(outputFile, lines);
if(regex_match(lines, endLoop))
{
cout << lines << endl;
num++;
} else {
cout << "[line " << num << " format error] " << lines << endl;
break;
}
//end facet
getline(outputFile, lines);
if(regex_match(lines, endfacet))
{
cout << lines << endl;
num++;
} else {
cout << "[line " << num << " format error] " << lines << endl;
break;
}
}
} else {
cout << "[line " << num << " format error] " << lines << endl;
}
}
outputFile.close();
}
return 0;
}
說明:
使用Regular Expression檢查ASCII STL檔案格式。

Simple drawing using the GD Libary

標題:GD繪圖範例
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include "stdafx.h"
#include <iostream>
#include "gd/gd.h"
#include "gd/gdfontg.h"
#include "gd/gdfontt.h"
#include "gd/gdfonts.h"
#include "gd/gdfontmb.h"
#include "gd/gdfontl.h"
#include <math.h>
using namespace std;
#pragma comment(lib, "lib/bgd.lib")
#define DEG 3.14159/180.
class ERR
{
private:
int kind;
public:
ERR(int k) : kind(k){};
char* message()
{
switch(kind)
{
case 0:
return "File Error!";
case 1:
return "GD Error!";
case 2:
return "File Write Error!";
case 3:
return "File Close Error!";
}
}
};
void drawstar(gdImagePtr image, float origx, float origy, float r, float angle, int color)
{
int i = 0;
float ptx[6],pty[6],pttx[6],ptty[6];
float temp1,temp2,temp3,temp4;
for(i=0;i<6;i++)
{
ptx[i]=origx+r*sin(72.*i*DEG+angle*DEG);
pty[i]=origy+r*cos(72.*i*DEG+angle*DEG);
temp1=cos(54.*DEG-72.*DEG*i-angle*DEG);
temp2=sin(54.*DEG-72.*DEG*i-angle*DEG);
temp3=sin(18.*DEG);
temp4=cos(36.*DEG);
pttx[i]=origx+r*temp3*temp1/temp4;
ptty[i]=origy+r*temp3*temp2/temp4;
}
for(i=0;i<5;i++)
{
gdImageLine(image, (int)ptx[i], (int)pty[i], (int)pttx[i], (int)ptty[i], color);
gdImageLine(image, (int)pttx[i], (int)ptty[i], (int)ptx[i+1], (int)pty[i+1], color);
}
}
int main(int argc, _TCHAR* argv[])
{
int i = 0;
FILE *out;
int size;
char *data;
gdImagePtr im = gdImageCreate(500, 500);
int white = gdImageColorAllocate(im, 255, 255, 255), //Background
black = gdImageColorAllocate(im, 0, 0, 0),
blue = gdImageColorAllocate(im, 0, 0, 255),
cyan = gdImageColorAllocate(im, 0, 255, 255),
green = gdImageColorAllocate(im, 128, 255, 0),
red = gdImageColorAllocate(im, 255, 0, 0),
purple = gdImageColorAllocate(im, 255, 0, 255),
orange = gdImageColorAllocate(im, 255, 128, 0),
yellow = gdImageColorAllocate(im, 255, 255, 0);
out = fopen("image.png", "wb");
try
{
if (out) {
for(i=0;i<72;i++)
{
drawstar(im, 250+5*i*sin(i*10*DEG), 250+5*i*cos(i*10*DEG), 30, 180, black);
}
data = (char *) gdImagePngPtr(im, &size);
if (!data) {
throw ERR(1);
}
if (fwrite(data, 1, size, out) != size) {
throw ERR(2);
}
if (fclose(out) != 0) {
throw ERR(3);
}
gdFree(data);
}
else
{
throw ERR(0);
}
}
catch(ERR e)
{
cout << e.message() << endl;
}
return 0;
}

說明:
簡單使用GD Library進行繪圖。

2013年7月15日 星期一

Exception Handling

標題:例外處理的方法
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include "stdafx.h"
#include <iostream>
#include <regex>
#include <fstream>
using namespace std;
class pos
{
public:
float x;
float y;
float z;
};
class ERR
{
private:
int kind;
public:
ERR(int k) : kind(k){}; //建構函式
char* message()
{
switch(kind)
{
case 0:
return "Error A";
case 1:
return "Error B";
case 2:
return "Error C";
}
}
};
void readfile(string path)
{
string lines = "";
ifstream File(path);
if (File.is_open()) //Check File
{
while(File.good())
{
getline(File, lines);
cout << lines << endl;
}
File.close();
}
}
int main(int argc, char *argv[])
{
switch(0) //Select Example
{
case 0:
{
//Example 1
int n = 0;
string str = "Hello";
try
{
cin >> n;
cout << str.at(n) << endl; //取得字串的第n個字元
}
catch (...)
{
cout << "Error!" << endl;
}
break;
}
case 1:
{
//Example 2
float num = 1;
try
{
cout << "num=";
cin >> num;
if(num == 0)
{
throw "Infinity!";
}
cout << "100/num=" << 100/num << endl;
}
catch (const char* message)
{
cout << message << endl;
}
break;
}
case 2:
{
//Example 3
try {
if(argc<2)
{
throw "Parameter error.";
}
char pathChar[1024];
regex pathRegex("([a-zA-Z]\:\\\\(?:[^\\\\]+\\\\)*.*)"); //"C:\\temp\\hello.txt"
cmatch pathMatch; //cmatch: Char Match
strcpy(pathChar, argv[1]); //Pointer to Char
if(regex_match(pathChar, pathMatch, pathRegex)) //char, cmatch, regexp
{
readfile(pathMatch[1].str());
}
else
{
throw "Path Error.";
}
}
catch(const char* message)
{
cout << message << endl;
}
break;
}
case 3:
{
//Example 4
pos p;
p.x = 1.1f;
p.y = 2.2f;
p.z = 3.3f;
cout << "(" << p.x << ", " << p.y << ", " << p.z << ")" << endl;
break;
}
case 4:
{
//Example 5
try
{
throw ERR(0);
}
catch(ERR e)
{
cout << e.message() << endl;
}
break;
}
}
system("pause");
return 0;
}

說明:
一般及搭配argc、argv、Regular Expression、Class例外處理的方法

Drag to read the file

標題:拖曳方式讀取檔案
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "stdafx.h"
#include <iostream>
#include <fstream> //ifstream
#include <sstream> //getline
using namespace std;
int main(const int argc, char *argv[])
{
/*int i = 0;
cout << "argc: " << argc << endl;
for(i=0;i<argc;i++)
{
cout << "*argv[" << i << "]: " << argv[i] << endl;
}*/
//Path Convert
char pathChar[1024];
string pathString = "";
strcpy(pathChar, argv[1]); //Pointer to Char
pathString.assign(pathChar); //Char to String
//ReadFile
string lines = "";
ifstream File(pathString);
if (File.is_open()) //Check File
{
while(File.good())
{
getline(File, lines);
cout << lines << endl;
}
File.close();
}
system("pause");
return 0;
}
Batch (Start.bat):


說明:
將檔案拖曳至exe執行檔,並藉由argc、argv取得路徑,轉換路徑變數型態後進行讀檔動作。
Batch檔是用來測試多行參數的讀取,須放在與執行檔相同之目錄。

2013年7月10日 星期三

Passing two-dimensional array to a function using pointer #2

標題:使用指標傳值的方式做矩陣相乘運算
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "stdafx.h"
#include <iostream>
using namespace std;
void multiply(float *matrixA, float *matrixB, float *matrixC, int p, int q, int r)
{
int i = 0, j = 0, k = 0;
float sum = 0.0f;
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
{
sum = 0.0f;
for (k = 0; k < q; k++)
{
sum += *(matrixA + i*q + k) * *(matrixB + k*r + j);
}
*(matrixC + i*r + j) = sum;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
const int p = 4, q = 2, r = 3;
int i = 0, j = 0;
float matrixA[p][q] = { //4x2矩陣
{3, -1},
{0, 3},
{1, 4},
{2, 1}
};
float matrixB[q][r] = { //2x3矩陣
{1, -2, 3},
{2, 1, 0}
};
float matrixC[p][r] = {}; //4x3矩陣
multiply(&matrixA[0][0], &matrixB[0][0], &matrixC[0][0], p, q, r);
//印出二維陣列資料
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
{
cout << matrixC[i][j] << "\t";
}
cout << endl;
}
return 0;
}

說明:
將3個二維陣列初始位址及陣列大小傳入函式,並在函式中針對指標內容進行矩陣相乘運算操作。

Get value using Regular Expression

標題:C/C++使用正規表示法取值
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include "stdafx.h"
#include <iostream>
#include <regex> //string lib here
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "--- Example 1 ---" << endl;
//String Match
string strA = "13393774";
smatch matchA;
regex regA("[0-9]+");
if(regex_match(strA, matchA, regA))
{
cout << atof(matchA[0].str().c_str()) << " is number." << endl;
} else {
cout << "Not a number." << endl;
}
cout << "--- Example 2 ---" << endl;
//String Match
string strB = "-4.472136e-001";
smatch matchB;
regex regB("[+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?");
if(regex_match(strB, matchB, regB))
{
cout << atof(matchB[0].str().c_str()) << " is number." << endl;
} else {
cout << "Not a number." << endl;
}
cout << "\n--- Example 3 ---" << endl;
//String Search
string strC = " facet normal 0.000000e+000 -4.472136e-001 8.944272e-001";
smatch matchC;
regex regC(" *facet normal \
([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) \
([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) \
([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?)");
if(regex_match(strC, matchC, regC))
{
cout << "Facet normal: (";
cout << atof(matchC[1].str().c_str()) << ", ";
cout << atof(matchC[2].str().c_str()) << ", ";
cout << atof(matchC[3].str().c_str()) << ")" << endl;
} else {
cout << "Not Match." << endl;
}
return 0;
}

說明:
在C/C++中使用正規表示式取得數值。

Passing two-dimensional array to a function using pointer

標題:使用指標傳入函式的方式進行多維陣列的處理
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "stdafx.h"
#include <iostream>
using namespace std;
// 陣列指標位址, 行數, 列數, 乘值
void multiply(float *matrix, int rows, int columns, float num)
{
int i = 0, j = 0;
for(i=0;i<rows;i++)
{
for(j=0;j<columns;j++)
{
*matrix *= num;
matrix++;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
const int m = 3, n = 4;
int i = 0, j = 0;
float matrixA[m][n] = { //3x4矩陣
{1, 2, 3, 4},
{0, 1, 0, 0},
{0, 0, 1, 0}
};
//傳入matrixA的記憶體起始儲存位址以進行處理
multiply(&matrixA[0][0], m, n , 5);
//印出二維陣列資料
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout << matrixA[i][j] << "\t";
}
cout << endl;
}
return 0;
}

說明:
將陣列初始位址及陣列大小傳入函式,並在函式中針對指標內容進行運算操作。

Passing array to a function

標題:使用一維陣列傳入函式的方式進行一維陣列的處理
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "stdafx.h"
#include <iostream>
using namespace std;
// 一維陣列, 乘值
float* multiply(float arr[], int m ,float num)
{
int i = 0;
for(i=0;i<m;i++)
{
arr[i] *= num;
}
return arr;
}
int _tmain(int argc, _TCHAR* argv[])
{
const int m = 5;
int i = 0, j = 0;
float arrA[m] = {1, 2, 3, 4, 5};
float *arrB = new float[m]; //宣告一動態陣列
arrB= multiply(arrA, m, 5); //傳入一維陣列
for(i=0;i<m;i++) //印出一維陣列資料
{
cout << arrB[i] << endl;
}
return 0;
}

說明:
直接向函式傳入一維陣列進行處理,再存入另一個陣列輸出。

2013年7月8日 星期一

Using Regular expression in C/C++

標題:C/C++使用正規表示法
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "stdafx.h"
#include <iostream>
#include <regex> //string lib here
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//String Match
string strA = "1337";
regex regA("[0-9]+");
if(regex_match(strA, regA))
{
cout << "A Match." << endl;
} else {
cout << "A Not Match." << endl;
}
//String Search
string strB = "cad23342";
regex regB("[0-9]");
if(regex_search(strB, regB))
{
cout << "B Match." << endl;
} else {
cout << "B Not Match." << endl;
}
//String Replace
string strC = "Hello I'm QQBoxy!!";
regex regC(" ");
string wordC = "\n";
cout << regex_replace(strC, regC, wordC) << endl;
//String Replace
string strD = "Hello I'm QQBoxy!!";
regex regD("a|e|i|o|u");
string wordD = "[$&]";
cout << regex_replace(strD, regD, wordD) << endl;
return 0;
}
說明:
在C/C++中正規表示式常用的三種語法。

Two ways to Read and Write Files

標題:C/C++兩種讀取文字檔的方法
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
//#include <iomanip>
//setprecision(4) "3.1415"
//setfill('Q') "QQ123"
//setw(5) " 123"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0, j = 0;
const char *filePath = "pi.xls";
remove(filePath); //Delete File
//VC++ -----------------------------------------------------
//Write File
ofstream outputFile(filePath, fstream::app); //fstream::out fstream::app
if (outputFile.is_open()) //Check File
{
for(j=1;j<10;j++)
{
for(i=1;i<10;i++)
{
outputFile << i << "*" << j << "=" << i*j << "\t";
}
outputFile << endl;
}
outputFile.close();
}
//Read File
string lines = "";
ifstream inputFile(filePath);
if (inputFile.is_open()) //Check File
{
while(inputFile.good())
{
getline(inputFile, lines);
cout << lines << endl;
}
inputFile.close();
}
//Standard C -----------------------------------------------------
//Write File
FILE *writeFile = fopen(filePath, "a");
if (writeFile) { //Check File
for(j=1;j<10;j++)
{
for(i=1;i<10;i++)
{
fprintf(writeFile, "%d*%d=%d\t", i, j, i*j);
}
fprintf(writeFile, "\n");
}
fclose(writeFile);
}
//Read File
char line[100] = ""; // Light!!
FILE *readFile = fopen(filePath, "r");
if (readFile) { //Check File
while(fgets(line, sizeof(line), readFile))
{
printf("%s", line);
}
fclose(readFile);
}
return 0;
}
說明:
使用fstream的方法讀寫檔案,以及使用C的fopen讀寫檔案的方法。

String conversion

標題:C/C++字串轉換
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream> //ostringstream
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//Character Sequences
//char c[13] = "CharVariable";
char c[13] = {'C', 'h', 'a', 'r', 'V', 'a', 'r', 'i', 'a', 'b', 'l', 'e', '\0'};
//Pointer
char *p = "Pointer";
//Class
string s = "String";
//String to Char
strcpy(c, s.c_str());
cout << c << endl;
//Char to String
s.assign(c);
cout << s << endl;
//Pointer to Char
strcpy(c, p);
cout << c << endl;
//Char to Pointer
p = &c[0];
cout << p << endl;
//String to Float
float num1 = 0.0f;
s = "233.42";
num1 = atof(s.c_str());
cout << num1 << endl;
//Float to String
float num2 = 233.42f;
ostringstream buffer;
buffer << num2;
s = buffer.str();
cout << s << endl;
return 0;
}
說明:
字元陣列、指標字串、VC字串,互相轉換。