2

Is this correct, it works OK

string str("in.dat");
ifstream fin(str.c_str(), ios::binary | ios::ate );
.
.
.
//Do I need to clear the string before assigning new name???
str = "out.dat";
ofstream fout(str.c_str(), ios::binary); //seems to work

Regards

5 Answers5

6

What everyone else has said is true. However, in the code you posted you could just as well have said:

ifstream fin( "in.dat", ios::binary | ios::ate );
ofstream fout( "out.dat", ios::binary ); 
  • I might add it's to be preferred. From a code-reading point of view. – xtofl May 18 '09 at 09:55
  • Depends if he uses the name for something else (like an error message) in the code he didn't post. I just wanted to make surwe he knew that he didn't always have to use s.c_str(). –  May 18 '09 at 09:57
2

What you did is correct. The = operator will overwrite string contents, it's normal scenario of reusing string variable. It will even probably not realloc any buffer, but reuse existing instead.

2

It's correct to do so. Assignment, in any language, means the object loses its old value and acquires a new one.

1

No, just assigning a new value is fine. It's the string class' responsibility to make sure that assignment works, that it doesn't introduce leaks.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

Though it's valid C++, it's not very nice C++.

The reader of your code needs to remember that the str variable is mutable, and serves a different purpose throughout your code file. When code is inserted between the second assignment of str and it's use as a filename, the reader may find it hard to find out what's in the variable.

It's always better to give your variables a sensible name; it then almost always becomes constant.

const char* inputpath("in.dat");
ifstream inputstream( inputpath, ... );

const char* outputpath("out.dat");
... lots of code
ofstream outputstream( outputpath, ... );
xtofl
  • 40,723
  • 12
  • 105
  • 192
  • 1
    The file stream constructors take a const char * as their first parameter, not a std:;string. –  May 18 '09 at 10:08