如何使用我的数组的mutator和accessor函数来显示输出?

时间:2015-02-10 21:20:27

标签: c++ arrays class

我无法理解以及如何通过使用我的类函数将我的数组中的变量分配给我的输出来从外部文件mycountrydata.txt显示输入。我的班级做错了什么,或者我放置或使用我的套装并做错了吗?还请告诉我为什么必须这样呢?

这是我的外部文件mycountrydata.txt:

  

中国

     

1357380000

     

9596961

     

法国

     

66616416

     

640679

     

美国

     

320206000

     

9857306

     

韩国

     

51302044

     

100210

     

日本

     

126434964

     

377,944

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class Country{

    private:
        string name;
        long population;
        double area;

    public:
        Country();
        Country(string, long, double);
        void setName(string);
        void setPopulation(long);
        void setArea(double);
        string getName();
        long getPopulation();
        double getArea();

  };

Country::Country(){
  name="?";
  population=0;
  area=0;
 }

Country::Country(string name1, long population1, double area1){
  name=name1;
  population=population1;
  area=area1;
}

void Country::setName(string name1){
 name=name1;
}

void Country::setPopulation(long population1){
  if(population1>=0.0)
    population=population1;
  else{
    population1=0.0;
    cout<< "Invalid number. Setting population to 0."<<endl;
 }
}

void Country::setArea(double area1){
if(area1>=0.0)
    area=area1;
 else{
    area1=0.0;
    cout<< "Invalid number. Setting area to 0."<<endl;
  }
}

string Country::getName(){
 return name;
}

long Country::getPopulation(){
 return population;
 }

double Country::getArea(){
 return area;
 }

int main(){


const int H=5;
string homename[H];
long homepopulation[H];
double homearea[H];
Country home(homename[H], homepopulation[H], homearea[H]);
ifstream infile("mycountrydata.txt");

    home.setName(homename[H]);
    home.setPopulation(homepopulation[H]);
    home.setArea(homearea[H]);

for(int i=0; i<H; i++){

    infile>>homename[i];
    infile>>homepopulation[i];
    infile>>homearea[i];

    cout<<"Country: "<<home.getName()<<endl;
    cout<<"Population: "<<home.getPopulation()<<endl;
    cout<<"Area: "<<home.getArea()<<endl<<endl; 

}
infile.close();
return 0;

}

1 个答案:

答案 0 :(得分:0)

可能就像这里:

Country home;
ifstream infile("mycountrydata.txt");
for(int i=0; i<H; i++){
    infile>>homename[i];
    infile>>homepopulation[i];
    infile>>homearea[i];

    home.setName(homename[i]);
    home.setPopulation(homepopulation[i]);
    home.setArea(homearea[i]);

    cout<<"Country: "<<home.getName()<<endl;
    cout<<"Population: "<<home.getPopulation()<<endl;
    cout<<"Area: "<<home.getArea()<<endl<<endl; 
}