我正在使用 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、字符串标题、字符串 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);
您当前正在以更简单的 fputs()
方式使用 fprintf()
。
关于来自 C++ 定义变量的 C++ Gnuplot 管道输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30762001/