opening a file using a string?
and yet another setback :
I wish to open a file using a string called file
but I am getting stuck using this code and canot figure out why.
cout << "Enter the name of the file you would like to open: ";
cin >> file;
stringFile.open(file);
stringFile >> list1;
any ideas would be helpful.
Strings aren't used for opening files, file streams are. Try something like:
#include <fstream>// ...std::string fileName;cout << "Enter the name of the file you would like to open: ";cin >> fileName;std::ifstream file(fileName);file >> list1;
here is the error sorry
c:\Documents and Settings\Owner\My Documents\Visual Studio Projects\P5150\linkedList_driver.cpp(26): error C2664: 'void std::basic_ifstream<_Elem,_Traits>::open(const char *,std::_Iosb<_Dummy>::openmode,int)' : cannot convert parameter 1 from 'std::string' to 'const char *'
with
[
_Elem=char,
_Traits=std::char_traits<char>,
_Dummy=int
]
c:\Documents and Settings\Owner\My Documents\Visual Studio Projects\P5150\linkedList_driver.cpp(26): error C2664: 'void std::basic_ifstream<_Elem,_Traits>::open(const char *,std::_Iosb<_Dummy>::openmode,int)' : cannot convert parameter 1 from 'std::string' to 'const char *'
with
[
_Elem=char,
_Traits=std::char_traits<char>,
_Dummy=int
]
Ah, you need to call std::string::c_str() to convert it to a const character array before passing it as an argument, like this:
EDIT: Beaten by 20 seconds!
stringFile.open(file.c_str());
EDIT: Beaten by 20 seconds!
Ok that worked like a champ converting to a c-string but I do not understand why that is the case.
regaurdless thanks for the help and if anyone cares to explain why that would be awesome :)
regaurdless thanks for the help and if anyone cares to explain why that would be awesome :)
Quote:Original post by polisasimo
Ok that worked like a champ converting to a c-string but I do not understand why that is the case.
regaurdless thanks for the help and if anyone cares to explain why that would be awesome :)
The std::string::open method only takes a const char*, not a std::string.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement