c++ - 写入文本文件并使用 c++ 和 gnuplot 绘图

标签 c++ ubuntu gnuplot

我是 C++ 的新手,我正在尝试将脚本的输出写入文本文件并使用 gnuplot 绘制输出。这是脚本:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <fftw3.h>
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;

int main(void)
{
    int i;
    double y;
    int N=256;
    double Fs=30000;//sampling frequency
    double  T=1/Fs;//sample time 
    double f=5000;//frequency
    double *in;
    fftw_complex *out;
    double t[N-1];//time vector 
    fftw_plan plan_forward;



    in = (double*) fftw_malloc(sizeof(double) * N);
    out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);


    for (int i=0; i< N;i++)
    {
        t[i]=i*T;
        in[i] =0.7 *sin(2*M_PI*f*t[i]);// generate sine waveform
        double multiplier = 0.5 * (1 - cos(2*M_PI*i/(N-1)));//Hanning Window
       in[i] = multiplier * in[i];
      }

    plan_forward = fftw_plan_dft_r2c_1d ( N, in, out, FFTW_ESTIMATE );

    fftw_execute ( plan_forward );

    for ( i = 0; i < N; i++ )
    {
    printf ( "  %4d  %12f\n", i, in[i] );
    }

fftw_destroy_plan ( plan_forward );
fftw_free ( in );
fftw_free ( out );
return 0;
}

所以输出是 i 和 in[i]

作为将我的输出写入文本文件的第一个尝试,我已将此代码添加到主函数内的脚本中:

fstream myfile;

myfile.open ("example.txt");

  for(i = 0; i < N; ++i)

    { myfile << i << std::endl;

      myfile << in[i] << std::endl;
    }

myfile.close();

我无法在两列中得到 i 和 in[i],所以我输入了

./Nameofthefile >stdout.txt 2>stderr.txt

在终端中,现在我的 stdout.txt 文件中有 i 和 in[i] 并排在两列中,如下所示:

 1      0.000092

 2      0.000368

等等。当我输入

gnuplot "stdout.txt"

在终端我得到这个错误:

0      0.000000
^
"stdout.txt", line 1: invalid command

我有两个问题:

1-如何修复这个错误

2- 如何在我的“example.txt”中将 i 和 in[i] 并排放置在两列中。我在“stdout.txt”中看到它的方式。谢谢。

最佳答案

不建议将您的某些头文件用于 C++。要使用以前的 C 标准库 header 的 C++ 版本,您可以指定以 c 为前缀且不带 .h< 的名称 扩展。

所以这些:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

会变成:

#include <cstdlib>
#include <cstdio>
#include <ctime>

您的问题是您没有提供 gnuplot 绘制图形所需的一切。您提供的是原始数据,但没有说明如何处理这些数据。

你需要输出这样的文件:

plot '-' using 1:2
1 0.000092
2 0.000368

因此您可以像这样在原始程序中添加绘图命令:

printf("plot '-' using 1:2\n"); // add this
for(i = 0; i < N; i++)
{
    printf("%4d  %12f\n", i, in[i]);
}

或者在你的另一个例子中是这样的:

std::fstream myfile;

myfile.open("example.txt");

myfile << "plot '-' using 1:2" << std::endl;
for(i = 0; i < N; ++i)
{
    myfile << i << " " << in[i] << std::endl;
}

myfile.close();

您可以使用以下方法绘制输出文件:

gnuplot -p < "stdcout.txt"

关于c++ - 写入文本文件并使用 c++ 和 gnuplot 绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32205217/

相关文章:

python - 绘制三元/三角图的库/工具

python - 在 xubuntu 上使用 gnuplot 保存图表

C++类继承变量

c++ - 结构编译错误 - 取消引用指向不完整类型的指针

MYSQL 根访问被拒绝(密码重置不起作用)

php - 如何使用 Cron 作业运行 PHP 脚本

gnuplot - 如何使用 GNUPlot 绘制 ApacheBench 输出文件的响应时间直方图?

C++ 文件 - MS Visual Studio

c++ - 模板:父类成员变量在继承类中不可见

regex - 如何删除双引号内的新行?