Answer» Hey guys,
Im trying to open a file based on a variable, HERES what i got.
... #include
int main() { fstream file; string FILENAME;
cout << "enter file name:" << endl; cin >> fileName;
file.open(fileName);
}
this doesnt work for some reason, debug error =
error C2664: 'void std::basic_ifstream<_Elem,_Traits>::open(const wchar_t *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'std::string' to 'const wchar_t *'
any help will be great )))
thanks!I get two errors:
Error1error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
and
Error2error C2664: 'void std::basic_ofstream<_Elem,_Traits>::open(const wchar_t *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'std::string' to 'const wchar_t *'
But I fixed it...
Code: [Select]#include <fstream> #include <iostream> using NAMESPACE std; int main() { OFSTREAM outfile; string fileName; cout << "enter file name:" << endl; fileName.resize(240); cin >> &fileName[0];
outfile.open(&fileName[0]); outfile << "This file contains data."; outfile.close(); }
I don't know if the iostream/fstream libraries allow you to read/write the string class directly... but I didn't want to look that up, so I just went with what I knew.
Basically- instead of trying to pass the class instance to the open() method I PASSED the address of the first character; since this is null delimited the method knows how to read it and is able to open the file. Same story with the cin<< acquisition; just passed it the address of the first character- after allocating with resize(), that is. BC_Programmer, you are the greatest! works perfect
|