-4

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?

pseyfert
  • 3,263
  • 3
  • 21
  • 47
Thanos
  • 594
  • 2
  • 7
  • 28
  • I think you need to [find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and start over with how file input and output works in C++ with streams. Hint: If you used `std::cout` to print anything you got the basics for output. – Some programmer dude Aug 24 '16 at 07:47
  • what does "(OK, through cint, using .L code.C++ :/)" mean? – M.M Sep 03 '16 at 14:06
  • @M.M ROOT uses an interpreter to run C++ code that is loaded via `.L filename.C`. Executing `.L filename.C+` compiles the code into a library rather than depending on an interpreter. The second `+` is a typo, but a harmless one- ROOT still interprets it the same. – Chris Sep 07 '16 at 21:01

1 Answers1

1

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.

Peter K
  • 1,372
  • 8
  • 24
  • 1
    The complaint comes because of [this conversion operator](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool). The `fprintf` expects a pointer, so the compiler uses the conversion operator. And since C++ is stronger typed than C the compiler will then complain about converting `void*` to `FILE*`. – Some programmer dude Aug 24 '16 at 07:50
  • @JoachimPileborg thanks for the explanation. I didn't know they had this implicit conversion before c++11. – Peter K Aug 24 '16 at 07:53
  • 1
    It was so a stream could be used in a boolean expression. Why they originally used pointers for this I don't know. – Some programmer dude Aug 24 '16 at 08:02