使用C ++中的gnuplot绘制几何图形

时间:2016-12-07 10:43:17

标签: c++ pipe

我已经用C ++编写了一个代码,它根据节点的坐标(彼此足够接近的点连接)找到几何图形的边缘。我现在想要绘制图形,将链接的坐标管道到Gnuplot。这看起来像这样:

FILE *pipe = popen("gnuplot -persist", "w");
fprintf(pipe, "\n");
fprintf(pipe, "set polar\n");
fprintf(pipe, "plot '-' with linespoints \n");

现在每次找到链接时(使用广度优先搜索算法),我都会

fprintf(pipe, "%g %g\n", RC[j].angle,RC[j].radius);
fprintf(pipe, "%g %g\n", RC[start[ptr]].angle,RC[start[ptr]].radius);
fprintf(pipe, "%g %g\n");

当搜索算法完成时,我以

结束
fprintf(pipe, "e\n");
fflush(pipe);
fclose(pipe);

然而,这并不会打印出我所期望的几何图形(远离的点会被连接起来)。如果我使用此过程将数据写入文件

outfile << RC[j].angle << ", " << RC[j].radius << endl;
outfile << RC[start[ptr]].angle << ", " << RC[start[ptr]].radius << endl;
outfile << " " << endl; 

我确实得到了我想要的图表。管道有什么问题?

1 个答案:

答案 0 :(得分:0)

从您的std::ostreamfprintf版本中,我可以看出区别很明显:您忘记了fprintf版本中的逗号(,)+空行:

fprintf(pipe, "%g, %g\n", RC[j].angle, RC[j].radius);
fprintf(pipe, "%g, %g\n", RC[start[ptr]].angle, RC[start[ptr]].radius);
fprintf(pipe, " \n");

作为替代方案,我建议使用C ++类而不是旧的C函数(未经测试):

class Pipe : public std::ofstream // in most cases this is bad, but ok here
{
public:
    Pipe( FILE* pf ) : _pg(pf) {}
    ~Pipe() { pclose(pf); }
    // copy-ctr(), op=(), ...
private:
    FILE _pf;
};

Pipe gnuplot(popen("gnuplot -persist", "w"));
gnuplot << "\n"
        << "set polar\n"
        << "plot '-' with linespoints\n";

for (...)
{
     gnuplot << RC[j].angle << ", " << RC[j].radius << "\n";
     gnuplot << RC[start[ptr]].angle << ", " << RC[start[ptr]].radius << "\n";
     gnuplot << " " << std::endl; 
}