使用getline读取文件/输入时出现分段错误
Segmentation fault while reading file/input with getline
我正在尝试开发一个简单的三维模型查看器,它应该能够逐行读取obj格式的文件。这看起来很简单,但是当std::getline
碰到eof
时,程序会以分段错误退出。
在这里,我制作了最少量的代码,这给了我一个segfault(我在这里使用std::cin
,这样我的程序就不会立即结束,但我实际上有机会向其中输入一些东西,并手动输入eof):
std::string line;
while(std::getline(std::cin, line))
{
std::cout<<line;
}
另一件需要注意的事情是,只有当包含eof的行为空时,此代码才会产生segfault,否则,如果在包含其他内容的行上输入eof,则循环只会继续
编辑:现在,我用尽可能小的代码复制了这个:
main.cpp
#include <iostream>
#include "Model.h"
int main(int argc, char* argv[])
{
std::string path = "/home/thor/Skrivebord/3d_files/Exported.obj";
obj::Model(path.c_str());
return 0;
}
型号.h
#ifndef MODEL_H_INCLUDED
#define MODEL_H_INCLUDED
namespace obj
{
class Model
{
public:
Model(const char* path);
};
}
#endif // MODEL_H_INCLUDED
型号.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
namespace obj
{
class Model
{
public:
Model(const char* path);
private:
std::string name = ""; // Remove this line, and all works.
};
Model::Model(const char* path)
{
std::string line;
while(std::getline(std::cin, line))
{
std::cout << line;
}
}
}
问题是您的代码有两个冲突的Model
声明。
在Model.cpp中,您有
class Model
{
public:
Model(const char* path);
private:
std::string name = ""; // Remove this line, and all works.
};
但在Model.h中,您有
class Model
{
public:
Model(const char* path);
};
您应该只有一个Model
的定义,将其放在Model.h中,将#include "Model.h"
放在Model.cpp 中
尽管逻辑很难理解,但这看起来像是一个错误。
void Face::AddVertex(float x, float y, float z)
{
if (vCnt > 3)
{
vertices[vCnt].SetPos(x, y, z);
++vCnt;
}
else
{
vertices.push_back(Vertex(x, y, z));
++vCnt;
}
}
<
而不是>
更符合逻辑,因为vertices
矢量最初的大小是3
void Face::AddVertex(float x, float y, float z)
{
if (vCnt < 3)
{
vertices[vCnt].SetPos(x, y, z);
++vCnt;
}
else
{
vertices.push_back(Vertex(x, y, z));
++vCnt;
}
}
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?