gpt4 book ai didi

c++ - ifstream 麻烦

转载 作者:行者123 更新时间:2023-11-28 00:29:33 27 4
gpt4 key购买 nike

我有以下代码。它编译得很好,但它告诉我字符串是“E#^$$@$$$$$$$”。有什么想法吗?

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);
}

播放列表:std::vector<Song*>Playlist;

最佳答案

这是有问题的行。

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

您正在存储一个指向内存的指针,该指针在您从文件中读取下一行文本后将无效。

将其更改为:

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

如果您的平台没有strdup,这里有一个简单的实现。

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

注意由于您在使用 strdup 时分配内存,因此您必须确保释放它。

您可以选择使用 new 来分配内存,因为您使用的是 C++。如果使用new 分配内存,则必须使用delete 释放内存。如果您使用 malloc 分配内存,如本答案所示,您必须使用 free 来释放内存。

关于c++ - ifstream 麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23435771/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com