[英]Segmentation fault while reading file/input with getline
I am trying to develop a simple 3d-model viewer, which should be able to read files line by line in the obj format. 我正在尝试开发一个简单的三维模型查看器,它应该能够以obj格式逐行读取文件。 This seemed to be very simple, however when
std::getline
hits eof
, the program exits with a segmentation fault. 这似乎很简单,但是当
std::getline
命中eof
,程序会以分段错误退出。
Here, I've made the smallest amount of code which gives me a segfault (I use std::cin
here, so that my program doesn't end immediately, but I actually get a chance to input some stuff into it, and manually enter an eof): 在这里,我制作了最少量的代码,它给了我一个段错误(我在这里使用
std::cin
,所以我的程序不会立即结束,但我实际上有机会输入一些东西,并手动输入eof):
std::string line;
while(std::getline(std::cin, line))
{
std::cout<<line;
}
Another thing to notice is, that this code will only produce a segfault if the line containing eof is empty, otherwise, if eof is entered on a line containing anything else, the loop simply carries on. 另一件需要注意的是,如果包含eof的行是空的,则此代码只会产生段错误,否则,如果在包含其他任何内容的行上输入eof,则循环只会继续。
Edit: Now, I've reproduced this with the smallest code possible: 编辑:现在,我用尽可能最小的代码重现了这个:
main.cpp 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;
}
Model.h Model.h
#ifndef MODEL_H_INCLUDED
#define MODEL_H_INCLUDED
namespace obj
{
class Model
{
public:
Model(const char* path);
};
}
#endif // MODEL_H_INCLUDED
Model.cpp Model.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;
}
}
}
This looks like an error although the logic is hard to follow. 这看起来像一个错误,虽然逻辑很难遵循。
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;
}
}
It's more logical with <
not >
since your vertices
vector is initially size 3 由于您的
vertices
向量最初为3,因此<
not >
更符合逻辑
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;
}
}
The problem is that your code has two conflicting declarations of Model
. 问题是你的代码有两个冲突的
Model
声明。
In Model.cpp you have 在Model.cpp中你有
class Model
{
public:
Model(const char* path);
private:
std::string name = ""; // Remove this line, and all works.
};
but in Model.h you have 但是在Model.h中你有
class Model
{
public:
Model(const char* path);
};
You should have one definition of Model
only, put that in Model.h and #include "Model.h"
in Model.cpp 您应该只有
Model
一个定义,将它放在Model.h中,并将#include "Model.h"
放在Model.cpp中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.