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

C++ Gnuplot pipe input from C++ defined variables

我正在使用 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(,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、字符串标题、字符串 xlabel 等

我能想到的都试过了,比如:

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

或:

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

不幸的是没有任何效果。

有没有人对我如何让它工作有任何想法?

提前致谢!

您想做的事情正是 fprintf() 的目的,请参阅 manual。这是一个例子:

int maximum = 500; // taken from user input maybe
fprintf(gnuplotPipe, "max=%d\n", maximum);

您目前正在以更简单的方式使用 fprintf() fputs()