#### Archived

This topic is now archived and is closed to further replies.

# C++ Newbie question

## Recommended Posts

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

##### Share on other sites
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);

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

"Try the best you can
try the best you can
the best you can is good enough"

##### Share on other sites
Im using an online book and this was one of the problems.

Here''s the full source:

  #include #include #include 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();}

##### Share on other sites
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.

##### Share on other sites
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.

##### Share on other sites
Thx MuteAngel.

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

##### Share on other sites
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.

• ### Forum Statistics

• Total Topics
628308
• Total Posts
2981974

• 9
• 13
• 11
• 12
• 11