【发布时间】:2014-11-04 03:24:44
【问题描述】:
我在尝试加载文本文件时遇到访问冲突写入位置错误。在调试时,我注意到我的“is_open()”和“good()”检查都通过了,因为我到达了“while (std::getline(myfile, line))。这怎么可能?更愚蠢的是,这非常函数在它自己的项目中完美运行,但由于某种原因,我在这里遇到了访问冲突错误。
// 标题
static bool LoadObj(std::string file, std::vector<GLfloat> &out_vertices, std::vector<GLfloat> &out_normals);
// CPP
bool Resources::LoadObj(std::string file, std::vector<GLfloat> &out_vertices, std::vector<GLfloat> &out_normals)
{
std::string line;
std::ifstream myfile(file);
if (myfile.is_open())
{
if (myfile.good())
{
while (std::getline(myfile, line))
{
if (!strncmp(line.c_str(), "v", 1))
{
std::string dummy;
std::stringstream ss(line);
ss >> dummy;
while (ss >> line)
{
out_vertices.push_back(std::stof(line));
std::cout << line;
}
}
}
}
}
return false;
}
【问题讨论】:
-
访问冲突与文件是否打开无关。该错误很可能存在于其他地方。
-
输入文件出现“写入位置”错误?
-
你正在写你不应该写的内存。抓住一个调试器,看看它发生在哪一行,看看你在滥用什么指针以及如何使用。
-
“更愚蠢的是,这个函数在它自己的项目中完美运行” - 更多的证据表明代码很好,但你的整个程序有未定义的行为,只是恰好在这里表现为崩溃。您可以尝试在 ValGrind 或其他分析工具下运行,甚至切换到调试模式或其他优化级别 - 这可能有助于崩溃发生在更接近导致它的代码的位置。
-
我在 VS2013 中调试,我看到我的 std::string 文件可以正常运行。但是 ifstream 说“读取字符串字符时出错”。我也尝试过使用 const char* 作为文件而不是字符串,但没有运气。我还设置了 std::ios::in 来指定这只是一个读取。
标签: c++ string fstream stringstream