File IO with std::string

Hi! I was looking at the tutorial on file I/O, and did a few experiments on it. After trying a few different things, I ran into a problem:
1
2
3
std::ifstream R;
std::string NAME = "this.txt";
R.open(NAME, std::ios::in);


gives me a compile error:

error: no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::open(std::string&, std::_Ios_Openmode)'

note: candidates are: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]


of course, I could change std::string to char* on line 2, but I've already got an std::string variable I've passed through 7 different header files, and converting all those to get here with a char* argument would require a major overhaul of my program.

...so I tried casting it with static_cast<char*>(NAME)
But I got conversion errors. After a little Google searching (returning nothing), I decided to try a stringstream. When I did, I got no errors, but my program crashed and returned 3.

So my question is: is there a valid way to pass a std::string variable through std::istream.open(char, std::char_traits<char>), or maybe an alternative method?

Use std::string::c_str() to get a const char* to its contents:
1
2
3
std::ifstream R;
std::string NAME = "this.txt";
R.open(NAME.c_str(), std::ios::in);
wow, I haven't seen .c_str() before, thats helpful. I'll remember that, thanks allot for your help.
Topic archived. No new replies allowed.