Domanda

I have the following code. It compiles fine, but it shows me that string is "E#^$$@$$$$$$$". Any ideas why?

ifstream InFile(Filename);
if (!InFile)
    return false;
std::string Name;
Song *pSong;

for (int a = 0; a < Playlist.size(); a++)
{
    delete Playlist[a];
}
Playlist.clear();

while (true)
{
    if (!InFile)
        break;

    pSong = new Song();

    std::getline(InFile, Name, '\n');
    pSong->File = const_cast<char*>(Name.c_str());
    std::getline(InFile, Name, '\n');
    pSong->Volume = atof(Name.c_str());

    Playlist.push_back(pSong);
}

Playlist: std::vector<Song*>Playlist;

È stato utile?

Soluzione

This is the problematic line.

pSong->File = const_cast<char*>(Name.c_str());

You are storing a pointer to a memory that won't be valid after you read the next line of text from the file.

Change it to:

pSong->File = strdup(Name.c_str());

If your platform doesn't have strdup, here's a simple implementation.

char* strdup(char const* s)
{
   char* ret = malloc(strlen(s)+1);
   strcpy(ret, s);
   return ret;
}

Caution Since you are allocating memory when you use strdup, you have to make sure that you deallocate it.

You have the option of using new to allocate memory since you are using C++. If you use new to allocate memory, you have to use delete to deallocate the memory. If you use malloc to allocate memory, like shown in this answer, you have to use free to deallocate the memory.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top