2016-12-01 53 views
0

當我執行我的程序時,我希望我的程序繪製圖形並顯示在屏幕上。但我不知道我該怎麼做。 這裏是示例C++代碼。如何在C++中使用GNUplot繪製圖形

#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; 
} 

這裏是頭文件。 void curve_plot(int n,double x [],double y [],string name);}};

curve_plot.cpp

#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; 
} 

回答

0

你想要什麼,運行在你的C++程序的gnuplot或者C++程序執行後運行呢?如果是第一個,請在return之前添加

system("gnuplot gnuplot_command_file"); 

聲明。當然,首先你必須建立一個字符串作爲system聲明的參數。

否則,只是在執行命令提示符

gnuplot your_command_file 
+0

從我的C++程序運行gnuplot的。我只是建立一個字符串並添加系統(「gnuplot command_file」);我想我還必須添加Gnu情節頭文件? – Rick

+0

gnuplot ist只是一個可以從命令行或程序執行的程序,所以是的。 – 2016-12-01 19:34:36

+0

所以我只是像你所說的那樣,我運行代碼,但仍然沒有顯示圖形,雖然程序執行得很好。附: :我正在使用visual studio 2015來執行我的程序 – Rick