简体   繁体   English

如何在cpp中使用struct读取文件

[英]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 当我输入值时:1、2、3、4、5 6,但输出如下

(-3.97922e-15,-3.97922e-15) (-3.97922e-15,-3.97922e-15) (-3.97922e-15,-3.97922e-15) (-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 . 并且您两次都打印了x ,所以我将第二个x固定为y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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