Search code examples
c++compiler-errorsprintfroot-framework

invalid conversion from ‘void*’ to ‘FILE*’ - ROOT


I am using cern's data analysis framework, ROOT. What I am trying to do is export in an ascii file the contents of a TH1F histogram. My sample code is the following

#include "TH1.h"
#include "TH1F.h"

#include <iostream>
#include <fstream>
using namespace std;

void histo2ascii(TH1* hist){

    ofstream myfile;
    myfile.open ("movie_small.txt");

    for (int i=1; i<=hist->GetNbinsX(); i++){
        if(hist->GetBinCenter(i)>5.e-3 && hist->GetBinCenter(i)<7.e-3){
            //myfile << (float) hist->GetBinCenter(i) << "\t" << hist->GetBinContent(i) << endl;
            fprintf(myfile, "%.17g \t %d", hist->GetBinCenter(i), (int) hist->GetBinContent(i));
        }
    }

    myfile.close();

}

The problem is that, when I compile it (OK, through cint, using .L code.C++ :/) I get the following error

invalid conversion from ‘void*’ to ‘FILE*’

at fprintf line.

Any idea on why this might be happening?


Solution

  • fprintf expects a FILE*, not an ofstream. You cannot use the c-style printing functions with c++ streams this way.

    Use the stream as you did in your commented out line just above the fprintf line. If you want to set the precision, use:

    myfile << std::setprecision(2) << hist->GetBinCenter(i).
    

    Don't forget to include <iomanip>. For a list of stream manipulators, see this page.

    Edit: As mentioned in the comments, myfile gets implicitly converted to void* since fprintf expects a pointer. This is why it complains about void* instead of ofstream.