C ++ Gnuplot管道输入来自C ++定义的变量

时间:2015-06-10 16:22:09

标签: c++ pipe gnuplot

我使用C ++使用以下代码将命令传递给gnuplot:

FILE *gnuplotPipe = popen("gnuplot -persist", "w");  // Open a pipe to gnuplot

if (gnuplotPipe) {   // If gnuplot is found

  fprintf(gnuplotPipe, "reset\n"); //gnuplot commands
  fprintf(gnuplotPipe, "n='500'\n");
  fprintf(gnuplotPipe, "max='1500'\n");
  fprintf(gnuplotPipe, "min='-1500\n");
  fprintf(gnuplotPipe, "width=(max-min)/n\n");
  fprintf(gnuplotPipe, "hist(x,width)=width*floor(x/width)+width/2.0\n");
  fprintf(gnuplotPipe, "set term png #output terminal and file\n");
  fprintf(gnuplotPipe, "set output 'Observable_Histogram.png'\n");
  fprintf(gnuplotPipe, "set xrange [min:max]\n");
  fprintf(gnuplotPipe, "set yrange [0:]\n");
  fprintf(gnuplotPipe, "set offset graph 0.05,0.05,0.05,0.0\n");
  fprintf(gnuplotPipe, "set xtics min,(max-min)/5,max\n");
  fprintf(gnuplotPipe, "set boxwidth width*0.9\n");
  fprintf(gnuplotPipe, "set style fill solid 0.5\n");
  fprintf(gnuplotPipe, "set tics out nomirror\n");
  fprintf(gnuplotPipe, "set xlabel 'Observable'\n");
  fprintf(gnuplotPipe, "set ylabel 'Counts'\n");
  fprintf(gnuplotPipe, "set title 'Observable'\n");
  fprintf(gnuplotPipe, "plot 'output.txt' u (hist($1,width)):(1.0) smooth freq w boxes lc rgb'green' notitle\n");

  fflush(gnuplotPipe); //flush pipe

  fprintf(gnuplotPipe,"exit \n");   // exit gnuplot
  pclose(gnuplotPipe);    //close pipe

}

这非常有效,但我希望它能够从c ++中先前定义的变量中获取输入 例如,我不想直接定义n =' 500',min =' -1500',max =' 1500'等,我想使用变量我已经在代码前面定义了(来自用户输入),即int n,int max,int min,string title,string xlabel等。

我已经尝试了我能想到的一切,例如:

fprintf(gnuplotPipe, "max=");
fprintf(gnuplotPipe, 'max');

或:

fprintf(gnuplotPipe, "max=" 'max' "\n");

并且不幸的是没有任何作用。

有没有人对如何使这项工作有任何想法?

提前致谢!

1 个答案:

答案 0 :(得分:2)

您要做的事情正是int maximum = 500; // taken from user input maybe fprintf(gnuplotPipe, "max=%d\n", maximum); 的用途,请参阅manual。这是一个例子:

fprintf()

您目前正在以更简单fputs()的方式使用<!DOCTYPE html> <html> <body> <h1>Getting server updates</h1> <div id="result"></div> <script> if(typeof(EventSource) !== "undefined") { var source = new EventSource("demo_sse.php"); source.onmessage = function(event) { document.getElementById("result").innerHTML += event.data + "<br>"; }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events..."; } </script> </body> </html>