无法读取wavefront文件

时间:2013-10-18 10:09:15

标签: c++ file opengl scanf strcmp

我对此代码有疑问:

    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)。

1 个答案:

答案 0 :(得分:0)

这是一个更加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",而不包含尾随空格。