帮我用C++写一个将txt文件数据画成直线并可视化的代码
时间: 2023-06-06 14:04:57 浏览: 76
好的,下面是将txt文件数据画成直线并可视化的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <graphics.h>
#define MAX_POINTS 1000
typedef struct point {
int x;
int y;
} Point;
Point points[MAX_POINTS];
int num_points = 0;
void draw_line(Point p1, Point p2) {
line(p1.x, p1.y, p2.x, p2.y);
}
void draw_graph(int maxx, int maxy) {
int gd = DETECT, gm;
initgraph(&gd, &gm, NULL);
setcolor(RED);
for (int i = 1; i < num_points; i++) {
draw_line(points[i-1], points[i]);
}
setcolor(WHITE);
line(0, maxy / 2, maxx, maxy / 2); // X轴
line(maxx / 2, 0, maxx / 2, maxy); // Y轴
closegraph();
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s filename\n", argv[0]);
exit(1);
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Can't open file %s\n", argv[1]);
exit(1);
}
int x, y;
int maxx = 0, maxy = 0;
while (fscanf(fp, "%d %d", &x, &y) == 2) {
Point p = {x, y};
points[num_points] = p;
num_points++;
if (x > maxx) maxx = x;
if (y > maxy) maxy = y;
}
fclose(fp);
draw_graph(maxx + 100, maxy + 100);
return 0;
}
```
这个代码读取一个包含点坐标的文本文件,并将它们连接成直线,然后在图形窗口中显示。
如果您需要进一步定制代码以满足您的需求,请在评论区留言,我将根据您的要求优化代码。
阅读全文