opening a file using a string?

Started by
9 comments, last by MaulingMonkey 18 years, 8 months ago
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.
Advertisement
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;
Error messages would be helpful. (I no longer bother taking shots in the dark.)
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
]
You'll need to use .c_str() on your string filename:

stringFile.open(file.c_str());
Blake's 7 RPG - a new project
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:
stringFile.open(file.c_str());


EDIT: Beaten by 20 seconds!
edit
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 :)
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.
Thanks for all the help I guess that is just one of those things a begining programmer has to accept :)

This topic is closed to new replies.

Advertisement