[英]How to pass array of input from an external file into main program?
我是C ++的新手,使用类和inputfile在输出中显示我的输入的程序遇到了麻烦。 我应该如何显示国家,人口和面积? 我收到如下错误消息:
第82行[错误]无效使用'Country :: Country'
第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;
}
构造函数是一个特殊的成员函数,不能通过这种方式直接调用:
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用作数组,但是您将它们声明为普通变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.