簡體   English   中英

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

[英]how to read file with struct in cpp

我有代碼

        #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)

您的錯誤很簡單

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM