[英]Access violation when using std::stringstream on windows
I am currently implementing a rudimentary file load function.我目前正在实现一个基本的文件加载功能。 When using a
std::stringstream
the program crashes with a access violation in the stringstream
destructor.使用
std::stringstream
,程序会因stringstream
析构函数中的访问冲突而崩溃。 Here is the function:这是函数:
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);
}
}
}
}
The file it loads looks like this (shortened for better readability):它加载的文件如下所示(缩短以提高可读性):
VERSION 1
0 14 254 0
and is saved with this function:并使用此功能保存:
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();
}
}
The error is:错误是:
Unhandled exception at 0x0f99a9ee (msvcp100d.dll) in FLAP.exe: 0xC0000005: Access violation reading location 0x00000004.
The error happens as soon as the stringstream
gets deleted implicitly...一旦
stringstream
被隐式删除,错误就会发生......
I use Visual Studio 2010 on Windows 7.我在 Windows 7 上使用 Visual Studio 2010。
Try this instead:试试这个:
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);
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.