okay i know how to use fstream and everything, but the prolem is that I want to use a variable in ithe open part.

exp const.

pretend all headers are included.

It works like this

ifstream infile;


but when I want to use a variable for the file it will read it does not work/

exp. using variable

ifstream infile;

string text = "text.txt";


it does not work, any helpful hit please.


The reason you are experiencing this problem is because fstream's open() command takes a "char *" paramater, not string.

void open(const char *filename, openmode mode = in | out);
> Opens a file. The stream's file buffer is associated with the specified file to perform the i/o operations.

The basic_string class represents a Sequence of characters. It contains all the usual operations of a Sequence, and, additionally, it contains standard string operations such as search and concatenation.

The basic_string class is parameterized by character type, and by that type's Character Traits. Most of the time, however, there is no need to use the basic_string template directly. Note also that, according to the C++ standard, basic_string has very unusual iterator invalidation semantics.

It is possible to convert a string to a character array. For example:

char str[255];
string s = " .... ";
strcpy( str, s.c_str() );

This is quite simple to understand.

const charT* c_str() const
> Returns a pointer to a null-terminated array of characters representing the string's contents.

The same with sending fstream the const char data. Instead of sending the string, send string.c_str(). For example:

ifstream infile;

string text = "text.txt";


If you have further questions, please feel free to ask.

- Stack Overflow

I didn't even know that command existed, or that fstream only takes chars, thanks alot. :cheesy:

This article has been dead for over six months. Start a new discussion instead.