In a program, you need to store the names and populations of 12 countries. Create arrays to store this information and then write the code needed to read the information into the arrays from a file named pop.dat. Write only the names of the countries to a file named country.dat.
#include <iostream>
usingnamespace std;
class country{
public:
string name;
int population;
country(string n,int p){
name = n;
population = p;
}
};
int main(){
country* l = new country[12];
ifstream infile;
infile.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
try {
infile.open("pop.dat");
string name;
int population;
for (int i = 0; i < 12; i++){
infile >> name >> population;
country c(name,population);
l[i] = c;
}
infile.close();
ofstream outfile;
outfile.open("country.dat");
for (int i = 0; i < 12; i++)
outfile.write(l[i].name+"\n");
outfile.close();
}
catch (std::ifstream::failure e) {
std::cerr << "The File ---- input.txt ---- is not Here \n";
}
return 0;
}
The thig is I still get errors and I don't know why, Did I write exactly what I asked to write or I wrote something else not related?
Please post the error messages exactly as they appear in your development environment, then perhaps someone can help explain what the error messages are telling you.
first of all you forgot to include <fstream> and <string> libraries
second mistake is by creating a array of country objects , country which has no default constructor , that is a constructor with no arguments
you could make use of vectors or some STL container to store your country class but i reccomend just use a struct
#include <iostream>
#include <fstream> // for std::ifstream and std::ofstream
#include <string> // for std::string
usingnamespace std;
struct country
{
int population;
string name;
};
int main(){
country countries[12]; //access members with "." operator like
// countries[3].population = 100
//if u allocate dinamically replace dot with "->"
ifstream in("pop.dat");
ofstream out("country.dat");
// do your things
in.close();
out.close();
return 0;
}
second mistake is by treating your data type country as an array. classes are not like structs
No, that part of the code is fine. Classes are very very similar to structs, the only significant difference being by default the members of a struct are public, while for a class they are private.
One thing that is missing is a default constructor. A class with no constructor at all is fine, but if you supply your own, you will often need, as in this case, to supply a default constructor.