Hey guys and girls, I am extremely new to coding, and I would appreciate some help. I am trying to write a code in which someone inputs a number, which is part of a file name, then I do stuff with the filename. Here is the part that I am having problems with...

void histogen()

double x;
// Get the run file
cout << "Which run number?" << endl;
cin >> x;
TFile y ("AMBER/data/runx/amhsk_runx.root");

Don't worry about the TFile command if you don't know it (you might, but if you don't, don't worry, it's not the problem), I am using this program in root to get data for a science experiment. I have looked on here for this problem, but they all dealt with more basic stuff where the filename was just something like i.txt. This one has the variable in twice, and is only part of the filename. Please help if you can. Thanks!

Use a stringstream:

#include<sstream>
//...
stringstream ss;
string first = "AMBER/data/run";
string middle = "/amhsk_run";
string last = ".root";
ss<<first<<x<<middle<<x<<last;

Use the ss.str() to get the string back.

Ok, please forgive my complete and utter stupidity, but I have no clue what to do next. You said use ss.str(), but I'm looking online, and I have no clue how to use it. Could you spell it out a bit more for me please?

I would imagine it would be TFile y(ss.str()); . If TFile takes a null terminated string then use ss.str().c_str()

umm...couple of ways, first is the easiest.

//option #1
string path = "AMBER/data/runx/amhsk_run"; 
string runNumber;
cin >> runNumber;
validate(runNumber);
path += runNumber + ".root";
//option # 2
string path = "AMBER/data/runx/amhsk_run*.root";
string runNumber;
cin >> runNumber;
path.replace( path.find('*'),1,runNumber) ;

umm...couple of ways, first is the easiest.

//option # 2
string path = "AMBER/data/runx/amhsk_run*.root";
string runNumber;
cin >> runNumber;
path.replace( path.find('*'),1,runNumber) ;

I think OP wants to replace both x'es. It doesn't change your code much but you'd need another find statement (and you'd have to adjust your replace call if runNumber was multiple digits, unless I misinterpreted it).

Yeah, I want to replace both x's in the filename. Also, the run numbers start at 1500 and go up by 1's. However, both x's in the filename are the same. So if I want run 1553, for example, the file name is
AMBER/data/run1553/amhsk_run1553.root

I would imagine it would be TFile y(ss.str()); . If TFile takes a null terminated string then use ss.str().c_str()

Thank you, the second one (the null terminated string) worked!

EDIT: Our posts crossed. Glad it worked.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.