string - implicit file extension using fopen in c++ -
i'm working on project i'm required take input file extension ".input". when run, user gives filename without file extension command line argument. take argument, argv[1] , open file specified can't work without user typing in entire filename
for example: user enters> run file.input //"run" executable, "file.input" filename
user supposed enter> run file
how file extension implied when using code:
fopen(argv[1],"r");
i tried using string, setting argv[1] , appending ".input" fopen won't accept string.
without seeing code, can't went wrong, suspect did this:
string filename = argv[1]; filename += ".input"; file* f = fopen(filename, "r"); // <--- error here
the issue here c++ std::string
type not char *
, what's expected fopen
. fix this, can use .c_str()
member function of std::string
type, gives null-terminated c-style string:
file* f = fopen(filename.c_str(), "r"); // no more errors!
as mentioned in comment, though, think you'd better off using ifstream
:
string filename = argv[1]; filename += ".input"; ifstream input(filename);
there's no longer need .c_str()
, , don't need worry leaking resources. everything's managed you. plus, it's type-safe!
Comments
Post a Comment