gpt4 book ai didi

c++ - 使用 getline 读取文件/输入时出现段错误

转载 作者:行者123 更新时间:2023-11-30 01:56:04 25 4
gpt4 key购买 nike

我正在尝试开发一个简单的 3d 模型查看器,它应该能够逐行读取 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;
}

模型.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 中

关于c++ - 使用 getline 读取文件/输入时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20176426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com