【问题标题】:Can't read wavefront file无法读取波前文件
【发布时间】:2013-10-18 10:09:15
【问题描述】:

我对这段代码有疑问:

    void readObj(const char* fName, std::vector<Vector3> &tempVertex, std::vector<Face3>  &tempFaces){
    FILE* file;
    file = fopen(fName, "r");
    if (file == 0)
        printf("#ERROR# can't open file!");
    else{
        while(true){
         char lineHeader[1000];
         int res = fscanf(file, "%s", lineHeader);
         if (res == EOF)
             break;
         else if (strcmp(lineHeader, "v ") == 0){
             Vector3 v;
             fscanf(file, "%f %f %f\n", &v.x, &v.y, &v.z);
             cout<<"tempVertex.push_back(v)";
             tempVertex.push_back(v);
         }
         else if (strcmp(lineHeader, "f ") == 0){
             Face3 f;
             fscanf(file, "%d %d %d", &f.a, &f.b, &f.c);
             cout<<"tempFaces.push_back(f)";
             tempFaces.push_back(f);
         }
         else{
            fscanf(file, "/n");
            cout<<"Nothing in this line!\n";
            }
        }
    }
}

我在这里使用它:

private: System::Void readFile(System::Object^  sender, System::EventArgs^  e) {
         vector<Vector3> test;  
         vector<Face3> ftest;
         reading::readObj("Text.txt", test, ftest);
     }

Test.txt:

    v 1.0f 2.0f 3.0
    f 1 2 3

而且它只生产:

    Nothing in this line! (x8)

而不是 tempVertex.push_back(v) 和 tempFaces.push_back(f)。

【问题讨论】:

  • 为什么在 C++ 程序中使用 C 函数?使用流和std::string
  • 另外,你为什么要扫描"/n"?对于"f" 行,不要忘记以fscanf 格式添加尾随空格。
  • 你的 else 不见了{}
  • 一个月前刚开始接触c++,不知道怎么跳行

标签: c++ file opengl scanf strcmp


【解决方案1】:

这是一个更 C++ 惯用的解决方案:

void readObj(const std::string& fName,
             std::vector<Vector3>& tempVertex,
             std::vector<Face3>& tempFaces)
{
    std::ifstream file(fName);

    std::string line;
    while (std::getline(file, line))
    {
        std::istringstream iss(line);

        char type;
        if (iss >> type)
        {
            if (type == 'v')
            {
                Vector3 v;
                if (iss >> v.x >> v.y >> v.z)
                    tempVertex.push_back(v);
            }
            else if (type == 'f')
            {
                Face3 f;
                if (iss >> f.a >> f.b >> f.c)
                    tempFaces.push_back(v);
            }
        }
    }
}

参考资料:


至于您当前的代码(如问题中所述),一个大问题是:

strcmp(lineHeader, "v ")
/* here -------------^ */

字符串lineHeader 只包含"v""f",不包含尾随空格。

【讨论】:

  • 它说:错误没有运算符“>>”匹配这些操作数
  • 我必须包含一些东西吗?
  • @user2894128 在哪一行?请编辑您的问题以包含 Vector3Face3 结构。
  • @user2894128 是的,您必须包含一些头文件。按照最后的参考链接查看哪些。
  • std::istringstream iss(line);
猜你喜欢
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 2012-03-07
  • 2016-06-17
  • 2016-10-19
  • 2016-08-29
  • 2013-12-27
  • 1970-01-01
相关资源
最近更新 更多