简体   繁体   中英

how to read file with struct in cpp

I have code

        #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;       
        }

when I entered value : 1 2, 3 4, 5 6 but output same as below

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

Your error is very simple

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

should be

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

that is

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

and you were printing x both times, so I fixed the second x to a y .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM