如何将输入数组从外部文件传递到主程序中
How to pass array of input from an external file into main program?
我是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作为数组,但您将它们声明为正常变量。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- 编译器每次编译主程序时都会编译所有包含的头文件吗
- 如何将输入数组从外部文件传递到主程序中
- 在不同的头文件中使用相同的类型,并将它们包含在主程序中
- 配置文件共享对象,无需重新编译主程序
- 如何在主程序 c++ 中使用我自己制作的数组头文件