The file United States.txt provides data on the 50 states. Each record contains
ID: 3866002 • Letter: T
Question
The file United States.txt provides data on the 50 states. Each record contains 5 pieces of information about a single state: name, abbreviation, date it entered the union, land area (in square miles) and population in the year 2015. The records are ordered by the date of entry into the union. The first three lines of the file are: Delaware, DE, 12/7/1787, 1954, 941875 Pennsylvania, PA, 12/12/1787, 44817, 12856989 New Jersey, NJ, 12/18/1787, 7417, 8969545 U.S. States. Create a class State with five properties to hold the information about a single state and a method that calculates the density (poeple per square mile) of the state. The book I'm using is An introduction to Programing Using Visual Basic. Tenth Edition. I need this to work on Visual Studio 2015.
Explanation / Answer
#include<iostream>
#include<string>
#include<sstream>
#include<fstream>
using namespace std;
class State{
private:
string name;
string abbreviation;
string date;
long land_area;
long population;
public:
State(){
name = "";
abbreviation = "";
date = "";
land_area = 0;
population = 0;
}
State(string nm, string abb, string date, long area, long pop){
name = nm;
abbreviation = abb;
date = date;
land_area = area;
population = pop;
}
double density(){
return ( population/land_area);
}
string getName(){
return name;
}
string getAbbreviation(){
return abbreviation;
}
string getDate(){
return date;
}
int getArea(){
return land_area;
}
long getPopulation(){
return population;
}
void setName(string nm){
name = nm;
}
void setAbbreviation(string abb){
abbreviation = abb;
}
void setDate(string d){
date = d;
}
void setArea(long a){
land_area = a;
}
void setPopulation(long pop){
population = pop;
}
};
int main(){
ifstream fin;
State list[50];
int count;
int field_count;
string line;
long area;
long pop;
fin.open("United_States.txt");
count = 0;
if (fin){
while(getline(fin,line))
{
stringstream linestream(line);
string value;
field_count= 0;
while(getline(linestream,value,','))
{
switch (field_count) {
case 0 : list[count].setName(value);
break;
case 1 : list[count].setAbbreviation(value);
break;
case 2 : list[count].setDate(value);
break;
case 3 : {
istringstream iss1(value);
iss1 >> area;
list[count].setArea(area);
break;
}
case 4 : {
istringstream iss2(value);
iss2 >> pop;
list[count].setPopulation(pop);
break;
}
}
field_count++;
if (field_count == 5)
field_count = 0;
}
count++;
}
fin.close();
for (int i = 0; i<count; i++){
cout << list[i].getName() << " Density:" << list[i].getPopulation()/list[i].getArea() << endl;
}
}
else {
cout << "Error in opening the file" << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.