
-----------------------------------
AnubisProgrammer
Mon Mar 20, 2006 3:13 pm

Problems opening a user defined .txt file
-----------------------------------
I'm guessing that it's obviously possible, I'm just not sure of the syntax to get ifstream to open a file that a user has created.


string filename;
cout>filename take an entire string, including spaces?

-----------------------------------
md
Mon Mar 20, 2006 4:49 pm


-----------------------------------
No, getline will get the entire line with white spaces cin >> filename will stop at hte first space. Either way works fine though.

As for the string error it's because yes; the function is expecting a character array and you are passing it a class. use the c_str() function to get a character array representing the string. Normally I'd recoment using std::strng simply becuse it keeps you from having to worry about things like memory management when all you want is a short string. Then just use c_str() when you need a character array.

-----------------------------------
AnubisProgrammer
Mon Mar 20, 2006 4:52 pm


-----------------------------------
yes....a character array.  Like I said, I'm trying to learn a lot of this myself, so could you possibly show an example of how to start a character array or how to use the c_str() function...because I have no idea...sorry.

-----------------------------------
md
Mon Mar 20, 2006 4:59 pm


-----------------------------------
Example fo converting to a character string:

	std::string test = "Blarg";
	const char *character_string;

	character_string = test.c_str();


If you don't know what a character string is, and even if you can't pass varaibles properly then really I dunno that you should be messing around with file IO.

-----------------------------------
AnubisProgrammer
Mon Mar 20, 2006 5:19 pm


-----------------------------------
I agree, without learning more I probably shouldn't be messing with file I/O.  However, my class has gotten an assignment that deals with I/O, even though the teacher hasn't taught I/O at all...as you can tell, I don't like my teacher.  He's the reason I ask so many questions on here, you guys actually answer them.  Anywho, I tried that conversion and hit a little problem.  Last question (I hope):

string file;
cin>>file;
const char *filename;
filename=file.c_str();
infile.open(filename);

with the proper ifstream infile and such, should that work?

-----------------------------------
md
Mon Mar 20, 2006 5:24 pm


-----------------------------------
Whoops! I totally forgot about that constant declaration... if you took that out it would work. Teh code I gave was not to show how to use c_str() in your code; just a very general example of how to call it.

You could much more easily use

string file;
cin>>file;
infile.open(file.c_str()); 

