The problem is that char* filename
is just a pointer to some memory containing characters. It does not own any memory itself.
When you use the command line argument, the program handles storing that string somewhere, and you get a pointer to it. When you try to read using cin >> filename
there isn't actually anywhere to store the read data.
Solution: Replace char* filename
with std::string filename
(and #include <string>
).
Then to open the output file, you need a c-style string (null terminated char
array). std::string
has a function for this. You would write
std::ofstream out(filename.c_str());
^^^^^
Or, in fact, if you can use a recent compiler with c++11 features, you don't even need to use c_str()
. A new std::ofstream
constructor has been added to accept a std::string
.