When I attempt to run this code it crashes. There are no error messages. When the program compiles and runs, it just displays the windows 7 message, "this program has stopped working.":
void readGameFile(string ** entries, int * num_entries, string ** story, int * num_lines)
{
ifstream madlib("madlibs1.txt");
string line;
getline(madlib, line);
*num_entries=stoi(line);
*entries=new string [*num_entries];
for (int i=0; i<*num_entries; i++)
{
getline(madlib,*entries[i]);
}
I did a few tests, and it seems to assign entries[0]
a value, and then crashes when attempting to assign entries[1]
a value. I am forced to use this function name, with those function parameters and parameter types specifically. I also may not use malloc, vector or other answers I've seen.
I think the issue is one of precedence: you almost certainly want:
getline( madlib, (*entries)[i]) );
Otherwise, you're indexing from the string**
, then dereferencing: *(entries[i])
.
You also want to check the results of getline
, possibly in the loop:
for ( int i = 0; madlib && i != *num_entries; ++ i )...
as well as before the std::stoi
.
And finally: I don't know why you are forced to use this function signature. It is horrible C++, and you should never write anything like this. Logically, std::vector<string>
would be a better solution, but even without it: your function has 4 out parameters. This would be better handled by returning a struct
. And failing that, out parameters in C++ are usually implemented by non-const reference, not by a pointer. While there are arguments for using the pointer in some cases, when it results in a pointer to a pointer, it's evil. If nothing else:
bool // Because we have to indicate whether it succeed or failed
readGameFile( std::string* &entries, int &num_entries, std::string* &story, int &num_lines )
// ...
(This actually looks more like it should be constructor, however, of a class with two data elements, entries
and story
.)
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.