2013-04-22 78 views
0

我想用C++編寫一個程序,用OpenGL讀取文件中的數據,然後縮放繪製數據。從一個文件讀取繪圖點,然後縮放

該文件中的數據是設置爲這樣:

 
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座標和\par標誌着y座標。

我寫的代碼似乎沒有工作。

#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(); 
     } 
    } 
+6

你是什麼意思「似乎沒有工作」?不工作如何?錯誤的結果?崩潰?讓獨角獸出現? – Bart 2013-04-22 04:56:40

+0

它可能整天坐在沙發上看電視。無論如何,從你的代碼中刪除所有GL的東西,你不需要它來演示讀取輸入文件的問題。對於單行,一次讀取浮點數,字符串,浮點數和字符串。檢查流狀態是否成功以檢測例如EOF。然後,驗證兩個字符串是否是期望的值,並最終處理這兩個座標。 – 2013-04-22 05:06:08

+0

它不繪製我給它的任何數據。我不知道這是因爲我讀取數據的方式是錯誤的,或者我的縮放比例是錯誤的,並且在窗口外繪製點。 – Deafsilver 2013-04-22 05:36:51

回答

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; 
} 
相關問題