C++ Newbie question

Started by
5 comments, last by Jolt 23 years, 5 months ago
I need to convert a string class into a char. I'm trying to open a ifstream file with a string class.
        
string fileName;
cin >> fileName;
ifstream in(fileName);        //error

    
ifstream only takes a char, not a string. I'm learning C++. Is this possible? Thx in advance. Edited by - Jolt on 10/29/00 5:22:28 PM
Advertisement
what is the string class you''re using?
the simplest way would be to do something like this:

    char fileName[24];  // won''t work if the filename''s                     // longer than 24cin >> fileName;ifstream in(fileName);    


if you give me more information about the string class i can probably help you use that..

------------------------
IUnknown *pUnkOuter

"Try the best you can
try the best you can
the best you can is good enough"
--Radiohead
------------------------IUnknown *pUnkOuter"Try the best you cantry the best you canthe best you can is good enough" --Radiohead
Im using an online book and this was one of the problems.

Here''s the full source:

    #include <iostream>#include <string>#include <fstream>using namespace std;class Text{private:	string fileData;			//holds the file datapublic:	Text() { };	Text(string fileName);	~Text() { };	string contents();};string Text::contents(){	return(fileData);};Text::Text(string fileName){	//open fileName	ifstream in(fileName);				//<---- ERROR!		//read the contents of the file in -> fileData	string line;	while(in >> line)		fileData += line + ''\n'';}void main(void){	string fn;	cout << "Enter the file name" << endl;	cin >> fn;	Text f(fn);	cout << endl;	cout << f.contents();}    


This should work :

    Text::Text(string fileName){  const char *cFileName = fileName.data();  // returns a const E (here a char) pointer  ifstream in(cFileName);}    


Now I remember there was a topic a little while ago about such a "conversion" and, if my memory''s right, this wasn''t the ideal solution to solve the problem.

Anyway, let me know if it solved your problem.
Sorry, forgot to include the rest of the method... And my user name too.

-----

This should work :

        Text::Text(string fileName){  const char *cFileName = fileName.data();  // returns a const E (here a char) pointer  ifstream in(cFileName);  //read the contents of the file in -> fileData string line;  string line;  while(in >> line)    fileData += line + ''\n'';}    


Now I remember there was a topic a little while ago about such a "conversion" and, if my memory''s right, this wasn''t the ideal solution to solve the problem.

Anyway, let me know if it solved your problem.
Thx MuteAngel.

I was stuck on that for over 2 hours, guess I shoulda bugged the author before I asked you all.

Jolt you got a few complicated answers to a simple problem.

fileName.c_str();

The c_str() string method returns a constant character pointer to the actual information used for the string.

This topic is closed to new replies.

Advertisement