【发布时间】:2014-07-26 09:15:19
【问题描述】:
我有这段代码:
char* mtlBuffer = readFromBinary(myfile[0]);
string mtlBufferStr = mtlBuffer;
if (mtlBufferStr != " ")
{
mtlFile.open(fileLocation + "/" + mtlBufferStr.substr(7));
if (mtlFile.is_open())
{
mtlFile.seekg(0, ios::end);
mtlLength = mtlFile.tellg();
mtlFile.seekg(0, ios::beg);
while (mtlFile.tellg() < mtlLength)
{
mtlFile.getline(mtlBuffer, 255);
mtlBufferStr = mtlBuffer;
}
}
}
上线:
mtlBufferStr = mtlBuffer;
我遇到了运行时错误:
Win32.exe 已触发断点。
这发生在 malloc 文件上。我已经破解了 mtlBuffer 存储的内容及其:
"# MTL 编写自 /Users/manapoly/Desktop/Yusup/Models/Land/Lamborghini/Aventador/Aventador/Avent.obj"
奇怪的是,如果我删除了这一行(并将 mtlBufferStr 与他需要包含的值进行比较):
mtlFile.getline(mtlBuffer, 255);
代码完美运行。为什么 getLine 程序会失败?
对不起我的英语。
【问题讨论】:
-
最有可能的原因是您从
char* mtlBuffer = readFromBinary(myfile[0]);获得的信息未正确终止NUL ('\0')! -
有点跑题:为什么不用
std::string::assign()而不是operator=? -
@IosifMurariu 可能是出于可读性原因。
-
为什么还有
char* mtlBuffer?为什么不直接分配给std::string?稍后您应该也可以使用std::stringgetline。 -
readFromBinary()究竟返回了什么?你可以给它写信吗?它足够大,可以容纳 255 个字符吗?这部分代码看起来很奇怪。
标签: c++ string file char malloc