Jump to content
  • Advertisement
Sign in to follow this  

opening a file using a string?

This topic is 4677 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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;

Share this post


Link to post
Share on other sites
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
]

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites
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 :)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!