Quantcast sprintf Text - Physics Forums Library

PDA

View Full Version : sprintf


neu
Jul25-08, 12:26 PM
Basically I've made a method to fill histograms and I need to use sprintf to define histogram titles with a wildcard (%s) that I call to be a string such as proton, antiproton etc depending on what dat I want to plot.

So anyway, here's an example of what I've done:

void PythiaMC_Analysis::fillMM_Histos(string histoID, double deltaPseudo) {

char histo1_name[100];
sprintf(histo1_name,"%s_Matched_deltaEta",histoID);
Fill(histo1,deltaPseudo);

}

Which I'd call after defining the histoID to be proton, antiproton or whatever. I've simplified the code to one plot for the sake of brevity.

SO basically I'm getting segmentation violations to do with this method, I have deduced that it occurs at the first occurance of sprintf. Am I using it incorrectly?

Any help would be much appreciated.

mgb_phys
Jul25-08, 12:40 PM
You should set at least the first element of histo1_name[] to 0, otherwise it is likely to be created full of random data (at least in a release build), a \0 is needed to mark the end of a C string.

Also sprintf is a c function, the %s matches a 'C' \0 terminated string, it doesn't know anything about the c++ string data type you are using.
Your string library probably has a getData method or can automatically convert it with something like (char*)histoID.