簡體   English   中英

使用getline讀取文件/輸入時出現分段錯誤

[英]Segmentation fault while reading file/input with getline

我正在嘗試開發一個簡單的三維模型查看器,它應該能夠以obj格式逐行讀取文件。 這似乎很簡單,但是當std::getline命中eof ,程序會以分段錯誤退出。

在這里,我制作了最少量的代碼,它給了我一個段錯誤(我在這里使用std::cin ,所以我的程序不會立即結束,但我實際上有機會輸入一些東西,並手動輸入eof):

std::string line;
while(std::getline(std::cin, line))
    {
        std::cout<<line;
    }

另一件需要注意的是,如果包含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

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

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

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,因此< 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;
    }
}

問題是你的代碼有兩個沖突的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中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM