2013-11-24 72 views
1

我正在嘗試開發一個簡單的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; 
     } 
    } 
} 
+0

只要'while(getline(cin,line))''沒有條件'eof()'。 – 0x499602D2

+0

我已經試過了,它仍然給我一個段錯誤。 – Lillesort131

+0

然後向我們展示您的實際代碼。 – 0x499602D2

回答

3

的問題是,你的代碼有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" .cpp

+0

準確地說我需要移動哪些代碼部分?如果我只是移動類本身,「Model :: Model(const char * path){...}'給了我一個錯誤。 – Lillesort131

+0

只需移動類本身**和**將'#include「Model.h」'添加到Model.cpp。 – john

+0

您應該只有一個類的定義。將該定義放在頭文件中,並在需要的地方包含頭文件。這是確保您在代碼中保持一致的類定義的技術。 – john

2

這看起來像一個錯誤,雖然邏輯很難遵循。

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; 
    } 
} 
+0

仍然不起作用,但感謝您找到它。 – Lillesort131

相關問題