Tuesday, July 14, 2009

C++: How do I set my file name as a variable so I can open whatever file I want during execution of program?

My codes looks something like this:





ifstream infile


infile.open("hours.dat");





infile%26gt;%26gt;Records[i].....so on.





I want to be able to write:


cin%26gt;%26gt;Variable


infile.open(Variable);


infile%26gt;%26gt;Records[i].....





This isn't working for me. What am I doing wrong. Is it even possible to use a variable for a file name? How do I do it? Thanks!

C++: How do I set my file name as a variable so I can open whatever file I want during execution of program?
void open ( const char * filename, ios_base::openmode mode = ios_base::in );








Your file name must be of type const char *.


Your variable "Variable" must be a string since you are using


cin %26gt;%26gt; Variable;





So, to open the file, use:


infile.open(Variable.c_str());


No comments:

Post a Comment