我正在嘗試開發一個簡單的3d模型查看器,它應該能夠逐行讀取obj格式的文件。這似乎很簡單,但是當std::getline
命中eof
時,程序退出並出現分段錯誤。使用getline讀取文件/輸入時的分段錯誤
在這裏,我做了最小的代碼,它給了我一個段錯誤(我在這裏使用了std::cin
,這樣我的程序不會立即結束,但我實際上有機會輸入一些東西進去,手動輸入EOF):
std::string line;
while(std::getline(std::cin, line))
{
std::cout<<line;
}
另一件事要注意的是,此代碼只會產生一個segfault如果包含EOF行是空的,否則,如果輸入一行含有別的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;
}
Model.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;
}
}
}
只要'while(getline(cin,line))''沒有條件'eof()'。 – 0x499602D2
我已經試過了,它仍然給我一個段錯誤。 – Lillesort131
然後向我們展示您的實際代碼。 – 0x499602D2