从 C++ 调用 GNU 绘图,无需用户输入
call gnu plot from c++ without user input
我在网上找到了这段代码。它使用 gnuplot从 c++ 中生成的数据制作一个绘图。但是,它需要用户输入,没有这些行就无法工作
printf("press enter to continue...");
getchar();
错误消息显示
line 0: warning: Skipping unreadable file "tempData"
line 0: No data in plot
有人知道解决这个问题的方法吗?我想在循环中使用此代码,而不是每次都调用输入......
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void plotResults(double* xData, double* yData, int dataSize);
int main() {
int i = 0;
int nIntervals = 100;
double intervalSize = 1.0;
double stepSize = intervalSize/nIntervals;
double* xData = (double*) malloc((nIntervals+1)*sizeof(double));
double* yData = (double*) malloc((nIntervals+1)*sizeof(double));
xData[0] = 0.0;
double x0 = 0.0;
for (i = 0; i < nIntervals; i++) {
x0 = xData[i];
xData[i+1] = x0 + stepSize;
}
for (i = 0; i <= nIntervals; i++) {
x0 = xData[i];
yData[i] = sin(x0)*cos(10*x0);
}
plotResults(xData,yData,nIntervals);
return 0;
}
void plotResults(double* xData, double* yData, int dataSize) {
FILE *gnuplotPipe,*tempDataFile;
char *tempDataFileName;
double x,y;
int i;
tempDataFileName = "tempData";
gnuplotPipe = popen("gnuplot","w");
if (gnuplotPipe) {
fprintf(gnuplotPipe,"plot "%s" with linesn",tempDataFileName);
fflush(gnuplotPipe);
tempDataFile = fopen(tempDataFileName,"w");
for (i=0; i <= dataSize; i++) {
x = xData[i];
y = yData[i];
fprintf(tempDataFile,"%lf %lfn",x,y);
}
fclose(tempDataFile);
printf("press enter to continue...");
getchar();
remove(tempDataFileName);
fprintf(gnuplotPipe,"exit n");
pclose(gnuplotPipe);
} else {
printf("gnuplot not found...");
}
}
我认为实际问题是您将临时文件删除到早期。我会重组代码以:
if (gnuplotPipe)
{
// Create the temp file
tempDataFile = fopen(tempDataFileName,"w");
for (i=0; i <= dataSize; i++)
{
x = xData[i];
y = yData[i];
fprintf(tempDataFile,"%lf %lfn",x,y);
}
fclose(tempDataFile);
// Send it to gnuplot
fprintf(gnuplotPipe,"plot "%s" with linesn",tempDataFileName);
fflush(gnuplotPipe);
fprintf(gnuplotPipe,"exit n");
pclose(gnuplotPipe);
// Clean up the temp file
remove(tempDataFileName);
}
这样,您最终不会在系统上获得很多临时文件。
另一个好办法是使 gnuplot 持久化,这样你就能够在管道关闭后看到绘图,只需在打开管道时添加一个-p
标志即可
gnuplotPipe = popen("gnuplot -p","w");
相关文章:
- C++如何通过用户输入删除列表元素
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 打印时有二叉树问题.用户输入不打印任何内容
- C ++奇怪的数组由用户输入
- 如何允许大写和小写用户输入?
- C++读取用户输入而不按回车键(Mac OS X),与Turbo Pascal中的读取键相同
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- 如何使用用户输入变量制作二维数组?
- 用户输入字符串的文件附加问题..C++
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?