如何将输入数组从外部文件传递到主程序中

How to pass array of input from an external file into main program?

本文关键字:主程序 文件 从外部 输入 数组      更新时间:2023-10-16

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

第82行[Error]"Country::Country"的使用无效

第89行[Error]数组下标的类型"long int[int]"无效

第93行[Error]数组下标的类型"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;
}
构造函数是一个特殊的成员函数,不能直接调用:
home.Country(homename, homepopulation, homearea);

long没有定义[]运算符,因此不能执行

infile>>homepopulation[i];

因为您早些时候声明了long homepopulation。中的错误也有同样的解释

infile>>homearea[i];

这些是解决代码中确切错误的答案,但它不能代替一个好的教学资源。请参阅此答案以获取一些有用的材料。

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

country home(homename, homepopulation, homearea); 

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