I'm trying to pass a file name with a string through a constructor, my code is this. I've removed some of the unnecessary stuff for simplicity.
// header file
Interpreter(const std::string location);
std::ifstream *file;
// end header file
// class file
Interpreter::Interpreter(const std::string location) {
file = new std::ifstream(location.c_str());
}
// end class file
However, the result is a "Debug Assertion Failed!".
Edit: As a fairly newbie C++ programmer (came from Java), I've taken the advice of an initializer list and this is my code now (in the header):
std::ifstream file;
Interpreter(const std::string location) {
file.open(location.c_str());
}
Yet I'm still getting the same error, any help? Thanks!
Edit 2:
int main(int argc, char** argv) {
Interpreter *interpreter = nullptr;
// check if arguments are provided
if (argc > 0) {
interpreter = new Interpreter(argv[1]);
} else {
// for now just use the debug script
error("No input files, using default script (debug)");
interpreter = new Interpreter("test.m");
}
interpreter->read();
delete interpreter;
return 0;
}
Edit 3
Did you mean this initializer list?
Interpreter::Interpreter(const std::string location): file(location) {
}
Edit 4
Final edit, thanks guys :) Turns out the problem was with the arguments
And argc>0 does not mean argv[1] is safe to access.
That's in the CPP file, and still gives the same result. D:
if (argc > 0) {
interpreter = new Interpreter(argv[1]);
This is not correct, if argc == 1
then argv[1]
is out of bounds, it should be
if (argc > 1) {
interpreter = new Interpreter(argv[1]);
As for the rest of the question, I would write the constructor like this:
Interpreter(const std::string location) : file(location) { }
(In C++11 you can construct an fstream
from a std::string
, if that doesn't work with your compiler then use location.c_str()
as you had previously:
Interpreter(const std::string location) : file(location.c_str()) { }
I would write your main
function like this:
int main(int argc, char** argv)
{
std::string file;
// check if arguments are provided
if (argc > 1) {
file = argv[1];
} else {
// for now just use the debug script
error("No input files, using default script (debug)");
file = "test.m";
}
Interpreter interpreter(file);
interpreter.read();
}
This has no new
and delete
and is simpler and clearer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.