0

我正在尝试使用 OpenGL 用 C++ 编写一个程序,该程序从文件中读取数据并缩放然后绘制数据。

文件中的数据设置如下:

0.017453293\tab 2.01623406\par
0.087266463\tab 2.056771249\par
0.191986218\tab 2.045176705\par
0.27925268\tab 1.971733548\par

\tab表示 x 坐标和表示\pary 坐标。

我编写的代码似乎不起作用。

    #include "stdafx.h"
    #include <stdlib.h>
    #define _USE_MATH_DEFINES
    #include <math.h>
    #include "glut.h"
    #include <iostream>
    #include <string>
    #include <fstream>

    int _tmain(int argc, char **argv) {
        void myInit(void);
        void myDisplay(void);
        glutInit(&argc, argv);
        glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
        glutInitWindowSize(640, 480);
        glutInitWindowPosition(100, 150);
        glutCreateWindow("CMPS389 HW2");
        glutDisplayFunc(myDisplay);
        myInit();
        glutMainLoop();
    }

    void myInit(void) {
        glClearColor(0.0, 0.0, 0.0, 0.0);
        glColor3f(1.0, 1.0, 1.0);
        glPointSize(4.0);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluOrtho2D(0.0, 640.0, 0.0, 480.0);
    }

    void myDisplay(void) {
        glClear(GL_COLOR_BUFFER_BIT);
        std::string words = "";
        float locX;
        float locY;

        std::ifstream fileN("curveData.txt");

        while(fileN != NULL) {
            fileN>>words;

            if (words == "\par") {
                            fileN>>locX;
            }
            if (words == "\tab") {
                fileN>>locY;
                glBegin(GL_LINES);
                    glVertex2f(locX*300, locY*300);
                glEnd();
            }
        glFlush();
        }
    }
4

1 回答 1

1

你需要真正减少这个。我只关注文件解析部分。这是解决问题的一种方法。请注意,以下内容不检查 \tab 或 \par 后缀。如果你真的需要,你可以自己添加。

#include <fstream>
#include <iostream>
#include <string>
#include <iterator>

struct position
{
    double x;
    double y;
};

std::istream& operator>>(std::istream& in, position& p)
{
    std::string terminator;
    in >> p.x;
    in >> terminator;
    in >> p.y;
    in >> terminator;

    return in;
}

int main()
{
    std::fstream file("c:\\temp\\testinput.txt");
    std::vector<position> data((std::istream_iterator<position>(file)), std::istream_iterator<position>());

    for(auto p : data)
        std::cout << "X: " << p.x << " Y: " << p.y << "\n";
    system("PAUSE");
    return 0;
}
于 2013-04-22T05:27:56.643 回答