在windows上使用std::stringstream时发生访问冲突
Access violation when using std::stringstream on windows
我目前正在实现一个基本的文件加载函数。当使用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
试试这个:
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);
}
}
}
}
}
}
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- 写入位置0x0000000C时发生访问冲突
- 我们可以访问一个不存在的联盟的成员吗
- C++从另一个类访问公共静态向量的正确方法是什么
- 我的简单if-else语句是如何无法访问的代码
- 从C++dll访问C#中的一行主要参数
- 概念TS检查忽略私有访问修饰符
- 访问被拒绝后,c++中的故障保护代码
- 在c++中访问int到类对象的映射时出错
- 我想访问std::unique_ptr中的一个特定元素
- 为什么示例代码访问IUnknown中已删除的内存
- C++:无法访问声明的受保护成员
- 通过指向指针数组的指针访问子类的属性
- 在windows上使用std::stringstream时发生访问冲突