2013-10-19 78 views
0

我不明白爲什麼我的程序打印出奇怪的數字,我相信這是地址編號....我試圖從文件中讀取數據,然後將它們存儲在類實例中。 ...文件的ID,X,Y,Z在一行....它有10行,因此我必須創建10個類實例...將很高興您的幫助... ^^從文件創建類

class planet 
{ 
public: 
    int id_planet; 
    float x,y,z; 
}; 

void report_planet_properties(planet& P) 
{ 
    cout<<"Planet's ID: "<<P.id_planet<<endl; 
    cout<<"Planet's coordinates (x,y,z): ("<<P.x<<","<<P.y<<","<<P.z<<")"<<endl; 
} 

planet* generate_planet(ifstream& fin) 
{ 
    planet* p = new planet; 
    fin >> (*p).id_planet; 
    fin >> (*p).x; 
    fin >> (*p).y; 
    fin >> (*p).z; 
    return (p); 
} 

int main() 
{ 
    planet* the_planets[10]; 
    int i=0; 
    ifstream f_inn ("route.txt"); 
    if (f_inn.is_open()) 
    { 
     f_inn >> i; 
     for(int j=0;j<i;j++) 
     { 
      the_planets[j]=generate_planet(f_inn); 
      report_planet_properties(*the_planets[i]); 
      delete the_planets[j]; 
     } 
     f_inn.close(); 
    } 
    else cout << "Unable to open file"; 
} 
+0

對不起....代碼行「f_inn >>我」這是因爲在文件中的第一行顯示我需要創建類THT的數量... –

回答

1

您的代碼會工作。

report_planet_properties(*the_planets[j]); 
+0

OMG ....大聲笑....我犯了一個粗心的錯誤那裏.....完全有效的....謝謝你... XD我會保存這兩種方法... –

+0

@AmosChew,heh你'歡迎,但你應該明確因爲它是面向對象的,所以請使用PhilipD的方法,請參閱我對他的答案的評論! – A4L

1

我不明白你的代碼的某些部分(例如,爲什麼你在generate_planet中創建行星的新實例),但我不是一個有經驗的C++程序員。但是,我修改了代碼,發現這個工作:

#include <iostream> 
#include <fstream> 

using namespace std; 

class planet 
{ 
private: 
    int id_planet; 
    float x,y,z; 
public: 
    void generate_planet(ifstream& fin); 
    void report_planet_properties(); 
}; 

void planet::report_planet_properties() { 
    cout << "\nPlanet's ID: " << id_planet << endl; 
    cout << "\nPlanet's coordinates (x,y,z): ("<< x <<","<< y <<","<< z<<")"<<endl; 
} 

void planet::generate_planet(ifstream& fin) { 

fin >> id_planet; 
fin >> x; 
fin >> y; 
fin >> z; 
} 

int main() { 

planet the_planets[10]; 
int i=0; 
ifstream f_inn("route.txt"); 
if (f_inn.is_open()) 
{ 
    f_inn >> i; 
    for(int j=0;j<i;j++) 
    { 
     the_planets[j].generate_planet(f_inn); 
     the_planets[j].report_planet_properties(); 
    } 
    f_inn.close(); 
} 
else cout << "Unable to open file\n"; 
return 0; 
} 

與route.txt:

2 
1 
4 
5 
6 
2 
7 
8 
9 

給出:

Planet's ID: 1 

Planet's coordinates (x,y,z): (4,5,6) 

Planet's ID: 2 

Planet's coordinates (x,y,z): (7,8,9) 

正如你所看到的功能generate_planet()和report_planet_properties()現在是planet類的方法。

也許這可以幫到你。如果你使用正確的索引the_planets

report_planet_properties(*the_planets[i]); 

在你必須使用你的循環變量j沒有i這是你的文件行星的數目上面一行

+0

不錯...我明白烏爾概念...編輯後得到正確的輸出....非常感謝你.. ^^ –

+0

+1面向對象重構,更進一步將是[重載](http://stackoverflow.com/questions/4421706 /運算符重載)類'星球'的'>>'運算符 – A4L

+0

hehehe ... ^^ yeap ...我將保存這兩種方法供將來參考...再次感謝你這麼多人... –