如何将外部文件的输入数组传递给主程序?

时间:2015-02-10 04:14:34

标签: c++ arrays class

我是C ++的新手,我使用类和inputfile在输出中显示输入时遇到问题。我应该如何显示国家,人口和地区?我收到如下错误消息:

第82行[错误]无效使用'国家/地区'

第89行[错误]类型无效' long int [int]'对于数组下标

第93行[错误]无效类型' double [int]'对于数组下标

这是我到目前为止所做的:

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

using namespace std;

class Country
{

    private:
        string name;
        long int 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(){

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

  home.setName(homename);
  home.setPopulation(homepopulation);
  home.setArea(homearea);
  home.Country(homename, homepopulation, homearea);
  for(int i=0; i<H; i++){

    cout<<"Enter the country's name: ";
    infile>>homename[i];
    cout<<endl;
    cout<<"Enter the country's population: ";
    infile>>homepopulation[i];
    cout<<endl;
    cout<<"Enter the country's area: ";
    cout<<endl;
    infile>>homearea[i];

  }
  infile.close();
  return 0;
}

2 个答案:

答案 0 :(得分:0)

构造函数是一个特殊的成员函数,不能以这种方式直接调用:

home.Country(homename, homepopulation, homearea);

long未定义[]运营商,因此您无法做到:

infile>>homepopulation[i];

从早些时候开始宣布long homepopulation

中的错误也是同样的解释
infile>>homearea[i];

这些是解决代码中确切错误的答案,但它并不能代替良好的教学资源。有关一些有用的资料,请参阅this answer

答案 1 :(得分:0)

country是一个构造函数,可以通过在main()替换country home的开头给出以下语句来调用它;

country home(homename, homepopulation, homearea); 

我想你想使用homepopulation和homearea作为数组,但你将它们声明为正常变量。