如何在cpp中读取带有struct的文件

时间:2016-05-08 17:57:11

标签: c++

我有代码

        #include <iostream>
        #include <fstream>
        using namespace std;

        struct triangle
        {
            float x;
            float y;
        };

        int main() {
            float x, y;

            struct triangle triangles[100];

            ofstream theFile("toado.txt");

            for(int index = 0; index < 3 ; index ++) {
                cout<<"please enter the coordinates x,y of point in of triangle : "<<endl;
                cin>>x>>y;
                theFile <<x<<" "<<y<<endl;
            }

             int i=0;

             ifstream fileRead("toado.txt");
             while(fileRead >> triangles[i].x >> triangles[i].y) {
                i++; 
             }
             cout<<"====================================================================="<<endl<<endl;
             for (int index = 0; index < i; index ++) {
                cout<<"the coordinates x, y of point "<<index+1<<" : ("<<triangles[i].x<<","<<triangles[i].x<<")"<<endl;
             }
             cout<<"====================================================================="<<endl<<endl;
            return 0;       
        }

当我输入值:1 2,3 4,5 6 但输出与下面相同

  

( - 3.97922e-15,-3.97922e-15)( - 3.97922e-15,-3.97922e-15)( - 3.97922e-15,-3.97922e-15)

1 个答案:

答案 0 :(得分:3)

您的错误很简单

cout<<"the coordinates x, y of point "<<index+1<<" : ("<<triangles[i].x<<","<<triangles[i].x<<")"<<endl;

应该是

cout<<"the coordinates x, y of point "<<index+1<<" : ("<<triangles[index].x<<","<<triangles[index].y<<")"<<endl;

triangles[  i  ].x  =>   triangles[  index  ].x

并且您同时打印x,因此我将第二个x修改为y