Sunday, July 12, 2009

How do I convert a c-style string of chars into a c++ style string of chars?

I'm getting a file name from argv and I need to use that file name to open the file using ifstream and get the contents of that file. But I'm having trouble compiling.. I have





string fileName(argv[1]);


ifstream myfile(fileName);


if (!myfile)


exit(1);





It compiles if i make it


ifstream myfile(fileName.c_str());


but I dont think it's what I want. Is there a way to make the fileName into a c++ string?

How do I convert a c-style string of chars into a c++ style string of chars?
Derive the class ifstream so that you can use string as a parameter in the constructor as well as char*.





eg.


class inputstream : public ifstream


{


public:


inputstream(string s)


: ifstream(s.c_str()) {}


}





This will make it what you want.
Reply:use argv[1] instead of fileName.


No comments:

Post a Comment