【问题标题】:Ifstream doesn't work with OpenGL/freeglutIfstream 不适用于 OpenGL/freeglut
【发布时间】:2015-12-29 13:52:11
【问题描述】:

如果我在使用 OpenGL/freeglut 时尝试使用 ifstream,程序会崩溃。我的代码:

#include <fstream>
#include <windows.h>
#include <GL/freeglut.h>
double x, y;
std::ifstream read("coordinates.txt");
void display() {
    glBegin(GL_LINE_STRIP);
        while (read >> x) //Crashes here
        {
            read >> y;
            glVertex2d(x, y);
        }
    glEnd();
    glFlush();
}
void key(unsigned char mychar, int x, int y) {
    if (mychar == 27) {
        exit(0);
    }
}
void initialize()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(-27, 27, -27, 27);
}
int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
    glutInitWindowSize(1920, 1080);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Lorenz Attractor");
    initialize();
    glutDisplayFunc(display);
    glutKeyboardFunc(key);
    glColor3d(0, 0, 1);
    glutFullScreen();
    glutMainLoopEvent();
    Sleep(60000);
}

坐标.txt:

1.1 1.03
2.5 2
3 5.3

我什至不需要包含 freeglut,我检查了一个以前运行良好的旧项目,现在它也崩溃了。将 Code::Blocks 与 MinGW 一起使用。为什么会发生这种情况?谢谢!

【问题讨论】:

  • 你有没有通过检查read.good()检查文件是否打开正确?
  • @BDL 输出1,还是不行,崩溃了。

标签: c++ opengl crash ifstream freeglut


【解决方案1】:

display 将被多次调用。每当需要重新绘制显示时都会调用它,例如当窗口进入视图时,另一个窗口移到它上面,调整窗口大小等。

display 读取文件。好吧,在它第一次读取文件之后,文件将是empty。毕竟,您在全局变量中打开了文件(仅供参考:从不这样做),并且您一直阅读直到文件为空。

不要在绘图时读取文件。将文件读入数据结构(例如,vector&lt;float&gt;)。在渲染循环之前执行此操作。然后,使用数据结构进行绘制。

【讨论】:

  • 我使用了 glutMainLoopEvent(),显示只会运行一次。此外,将文件存储在数据结构中不是一种选择,因为我最终需要它来从成千上万个坐标中绘制图形,所以我很快就会耗尽内存。这也不能解释为什么 ifstream 根本不起作用,即使没有 freeglut。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 2019-03-03
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多