我目前正在实现一个基本的文件加载功能。使用std::stringstream
时,程序会因stringstream
析构函数中的访问冲突而崩溃。这是功能:
void macro_storage_t::load(std::string filename)
{
std::ifstream file(filename);
if (file.is_open())
{
clear();
char line_c[4096];
while (file.getline(line_c, 4096))
{
std::string line(line_c);
if (line.find("VERSION") == std::string::npos)
{
std::stringstream ss(std::stringstream::in | std::stringstream::out);
int a, b, c, d;
ss << line;
ss >> a >> b >> c >> d;
entry_t entry;
entry.timestamp = a;
entry.type = static_cast<entry_type_t>(b);
entry.button = static_cast<button_t>(c);
entry.key = static_cast<BYTE>(d);
}
}
}
}
它加载的文件看起来像这样(缩短以获得更好的可读性):
VERSION 1
0 14 254 0
并使用此功能保存:
void macro_storage_t::save(std::string filename)
{
std::ofstream file(filename, std::ios::trunc);
if (file.is_open())
{
file << "VERSION " << MACRO_VERSION << std::endl;
for (std::vector<entry_t>::iterator it = entry_list_.begin(); it != entry_list_.end(); ++it)
{
entry_t entry = *it;
file << (int)entry.timestamp << " " << (int)entry.type << " " << (int)entry.button << " " << (int)entry.key << std::endl;
}
file.close();
}
}
错误是:
Unhandled exception at 0x0f99a9ee (msvcp100d.dll) in FLAP.exe: 0xC0000005: Access violation reading location 0x00000004.
一旦stringstream
被隐式删除,就会发生错误...
我在Windows 7上使用Visual Studio 2010。
答案 0 :(得分:0)
请改为尝试:
void macro_storage_t::load(std::string filename)
{
std::ifstream file(filename);
if (file.is_open())
{
clear();
std::string line;
if (std::getline(file, line))
{
if (line.substr(0, 8) == "VERSION ")
{
// optional: read the actual version number from the line,
// if it affects how the following values must be read...
while (std::getline(file, line))
{
std::istringstream ss(line);
int a, b, c, d;
if (ss >> a >> b >> c >> d)
{
entry_t entry;
entry.timestamp = a;
entry.type = static_cast<entry_type_t>(b);
entry.button = static_cast<button_t>(c);
entry.key = static_cast<BYTE>(d);
entry_list_.push_back(entry);
}
}
}
}
}
}