I have a trouble reading a .txt file into a char* array.
I have a levels.txt file that looks like this:
level1.txt
level2.txt
I have my array defined inside a class as
char* levels[10];
And my parsing function looks like this:
// Parse the level list file
int Environment::parseLevels() {
ifstream data;
data.open("levels.txt");
char buf[64];
for (int i=0; i<sizeof(levels); i++) {
data.getline(buf, 64);
levels[0] = strtok(buf, " ");
}
}
If I do cout << levels[0]; right after
levels[0] = strtok(buf, " ");
then I get a fine output. However, when I try to cout << levels[0]; from somewhere else, nothing gets displayed.
What am I doing wrong?
Thank you in advance!
The pointer returned by
strtokis not going to point to valid memory forever since the buffer that you’re tokenizing is declared on the stack. You’ll need to actually copy the string being pointed to by the return pointer ofstrtok, not the pointer itself if you want to use the string outside the function body.So basically modify your code to the following:
Then in the destructor for your
Environmentobject, make sure to have some loop to free the memory being pointed to by each of the members of thelevelsarray that are pointing to memory allocated vianew []. You do this by callingdelete []