Ifstream :: open () using string as parameter

I am trying to create a program that requests a file that the user would like to read, and when I try to execute myfile.open(fileName) , I get the error: "there is no corresponding function to call std::basic_ifstream<char, std::char_traits<char> >::open(std::string&)' "into this string.

 string filename; cout<<"Enter name of file: "; cin>>filename; ifstream myFile; myFile.open(filename); //where the error occurs. myFile.close(); 
+4
source share
1 answer

In the previous version of C ++ (C ++ 03), open() only accepts const char * for the first parameter instead of std::string . The correct way to call it:

 myFile.open(filename.c_str()); 

In current C ++ (C ++ 11), this code is fine, so see if you can tell your compiler that it supports it.

+11
source

All Articles