我需要帮助从C ++中的文件解析

时间:2011-03-23 06:18:49

标签: c++ parsing opengl model

好吧基本上我有这个带有数字和字母的文本文件,它应该代表多边形的顶点。这部分并不重要,因为我无法从文件解析为int。到目前为止,该函数看起来像:

    void parseModel(void)
{
    int num_vertices, num_faces;
    char data[255];
    ifstream ifs("rect-skinny.d");
    ifs.getline(data, 255);
    istrstream ins(data);
    ins >> num_vertices;
    cout << num_vertices << endl;
    ifs.close();
}

我尝试了许多不同的方法,这些方法都给了我不同但错误的答案。由于某种原因,这个输出数字-858993460。其他时候,当我尝试单独打印数据时,它只会输出封闭的括号。我无法弄清楚我做错了什么,因为这似乎应该有效。输入文件是:

 data    8    6
 -0.5   1.0   0.3
 0.5   1.0   0.3
 0.5   -1.0   0.3
 -0.5   -1.0   0.3
 -0.5   1.0   -0.3
 0.5   1.0   -0.3
 0.5   -1.0   -0.3
 -0.5   -1.0   -0.3
   4   1   2   3   4
   4   1   5   6   2
   4   2   6   7   3
   4   5   8   7   6
   4   1   4   8   5
   4   3   7   8   4

基本上我现在尝试做的就是获取第一行并将这些数字分别放入num_vertices和num_faces中。

3 个答案:

答案 0 :(得分:2)

阅读文本字符串“data”后,它将包含“data 8 6”。

ins >> num_vertices;行会尝试读取一个整数,但会找到“data 8 6”,因此会失败。尝试这样的事情:

void parseModel(void)
{
    int num_vertices, num_faces;
    char data[255];
    std::ifstream ifs("rect-skinny.d");
    ifs.getline(data, 255);       // data contains "data    8    6"
    std::istrstream ins(data);    // ins  contains "data    8    6"
    ins.ignore(4, ' ');           // ins  contains "    8    6"
    ins >> num_vertices;
    std::cout << num_vertices << endl;
    ifs.close();
}

答案 1 :(得分:1)

这就是我如何处理这个问题....

如果失败,您可能只想在每个数据之后组织文件并返回。无论如何,你的生活将变得无比轻松,你的数据也会在阵列中。

如果您确实已经开始使用char数组,则可以将字符串更改为char数组。

void parseModel(void)
{
    //will read in heading data first, then parse model data
    //you could alternatively store your header data in a struct
    //or class for better organization

    //work with strings, not raw char arrays
    string data;
    int num_vertices;
    int num_faces;

    //open the stream
    ifstream ifs("rect-skinny.d");
    if(!ifs.is_open())
    {
        cout << "ERROR- ifstream NOT OPEN\n";
    }

    //read in heading data
    ifs >> data;
    ifs >> num_vertices;
    ifs >> num_faces;

    //array of vertex data
    float vertices[num_vertices];
    //array of faces data
    int   faces[num_faces];

    //loop through all the vertices, reading each into the array
    for(int i = 0; i < num_vertices; i++)
    {
        ifs >> vertices[i];
    }
    //do the same for the faces
    for(int n = 0; n < num_faces; n++)
    {
        ifs >> faces[n];
    }
    //closing the stream
    ifs.close();
}

答案 2 :(得分:0)

您可能只想考虑使用fscanf。