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;

infile.open("text.txt");
...
}

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";

infile.open(text);

...
}
it does not work, any helpful hit please.

Greetings,

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

open()
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.

basic_string
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.

Converting
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";

infile.open(text.c_str());

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:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.