when I execute my program, I want my program to plot a graph and display on the screen. But I am not sure how do I do that.
Here is the example C++ code.
#include "stdafx.h"
# include <cstdlib>
# include <iostream>
# include <iomanip>
# include <cmath>
using namespace std;
# include "curve_plot.h"
int main();
int main()
{
int i;
int n;
double *x;
double *y;
cout << "\n";
cout << "CURVE_PLOT_PRB:\n";
cout << " Demonstrate how CURVE_PLOT can be used.\n";
// Set up some data to plot.
n = 51;
x = new double[n];
y = new double[n];
for (i = 0; i < 51; i++)
{
x[i] = (double)(i) / 10.0;
y[i] = x[i] * cos(x[i]);
}
// Send the data to curve_plot.
curve_plot(n, x, y, "curve_plot");
// Free memory.
delete[] x;
delete[] y;
return 0;
}
#include "stdafx.h"
# include <cstdlib>
# include <iostream>
# include <iomanip>
# include <fstream>
#include <string>
using namespace std;
# include "curve_plot.h"
void curve_plot(int n, double x[], double y[], string name)
{
string command_filename;
ofstream command_unit;
string data_filename;
ofstream data_unit;
int i;
string plot_filename;
// Write the data file.
data_filename = name + "_data.txt";
data_unit.open(data_filename.c_str());
for (i = 0; i < n; i++)
{
data_unit << x[i] << " "
<< y[i] << "\n";
}
data_unit.close();
cout << "\n";
cout << " Plot data written to the file \"" << data_filename << "\".\n";
// Write the command file.
command_filename = name + "_commands.txt";
command_unit.open(command_filename.c_str());
command_unit << "set term png\n";
plot_filename = name + ".png";
command_unit << "set output \"" << plot_filename << "\"\n";
command_unit << "set grid\n";
command_unit << "set style data lines\n";
command_unit << "unset key\n";
command_unit << "set xlabel '<---X--->'\n";
command_unit << "set ylabel '<---Y--->'\n";
command_unit << "set timestamp\n";
command_unit << "plot \"" << data_filename << "\" using 1:2 with lines lw 3\n";
command_unit << "quit\n";
command_unit.close();
cout << " Command data written to \"" << command_filename << "\".\n";
return;
}
What do you want, to run gnuplot from your C++ program or to run it after your C++ program execution? If it's the first, add
system("gnuplot gnuplot_command_file");
just before
return statement. Of course, firstly you have to build a character string as a paramater of the
system statement.
Otherwise, just execute in your command prompt
gnuplot your_command_file