SlideShare a Scribd company logo
CountryData.cpp
*EDIT THIS ONE*
#include
#include
#include "CountryData.h"
#include "utilities.h"
using namespace std;
CountryData::CountryData(const string& n, double p1, double p2) : name(n), pop1980(p1),
pop2010(p2)
{
}
string getName() const {
return name(n);
}
double calcGrowth() const {
return (pop2010(p2) - pop1980(p1)) / pop1980(p2);
}
private:
string name_;
double pop1980(p1);
double pop2010(p2);
}
double fieldToDouble(const string& field) {
try {
return stod(field);
}
catch (...) {
throw runtime_error("invalid floating-point field: " + field);
}
}
vector split(const string& s, char sep) {
vector fields;
stringstream ss(s);
string field;
while (getline(ss, field, sep)) {
fields.push_back(field);
}
return fields;
}
CountryData parseCountryData(const string& line) {
vector fields = split(line, ',');
if (fields.size() != 12) {
throw runtime_error("invalid line: " + line);
}
string name = fields[0];
double pop1980 = fieldToDouble(fields[1]);
double pop2010 = fieldToDouble(fields[11]);
return CountryData(name, pop1980, pop2010);
}
vector readCountryData(const string& filename) {
vector countryDataList;
ifstream infile(filename);
if (!infile) {
throw runtime_error("unable to open file: " + filename);
}
string line;
while (getline(infile, line)) {
try {
CountryData countryData = parseCountryData(line);
countryDataList.push_back(countryData);
}
catch (const runtime_error&) {
// ignore the error; just don't add this one to the vector
}
}
return countryDataList;
}
vector ReadCountryData(const string & filename)
{
vector data;
ifstream ifs{ filename };
string line;
// Read the header line
getline(ifs, line);
while (getline(ifs, line)) {
try {
CountryData cd = ParseCountryData(line);
data.push_back(cd);
}
catch (runtime_error & e) {
string error{ e.what() };
}
}
return data;
}
CountrtyData.h
#pragma once
#include
#include
class CountryData
{
public:
CountryData(const std::string & n, double p1, double p2);
std::string GetName() const;
double CalcGrowth() const;
private:
std::string name;
double pop1980;
double pop2010;
};
CountryData ParseCountryData(const std::string& line);
std::vector ReadCountryData(const std::string& filename);
utilities.h
#pragma once
#include
#include
// Split a string into sub-strings based on the given
// delimiter. For example, if the input is
//
// Ron,Ginny,George,Fred,Percy,Bill,Charlie
//
// the output is a 7-element vector with
// the following entries:
//
// [0] = "Ron"
// [1] = "Ginny"
// [2] = "George"
// [3] = "Fred"
// [4] = "Percy"
// [5] = "Bill"
// [6] = "Charlie"
//
std::vector split(const std::string& s, char seperator);
// Converts a database field string to an integer.
// If the field cannot be converted to an int,
// a runtime_error exception is thrown.
int fieldToInt(const std::string & field);
// Converts a database field to a double.
// If the field cannot be converted to an double,
// a runtime_error exception is thrown.
double fieldToDouble(const std::string & field);
utilities.cpp
#include
#include
#include "utilities.h"
std::vector split(const std::string & s, char sep)
{
std::vector fields;
size_t i = 0;
size_t len = s.length();
while (i < len) {
// Skip characters until we find a separator.
size_t j = i;
while ((i < len) && (s[i] != sep))
i++;
// Add this field - which may be empty! - to the output.
if (j == i)
fields.emplace_back();
else
fields.emplace_back(&s[j], i - j);
// Skip past the separator.
i++;
// If this put us at the end of the string,
// we need to account for the blank field at
// the end.
if (i == len)
fields.emplace_back();
}
return fields;
}
int fieldToInt(const std::string & field)
{
if (field.length() == 0)
throw std::runtime_error("Cannot convert 0-length string");
if (field == "--" || (field == "NA"))
throw std::runtime_error("No data provided");
return strtol(field.c_str(), NULL, 10);
}
double fieldToDouble(const std::string & field)
{
if (field.length() == 0)
throw std::runtime_error("Cannot convert 0-length string");
if (field == "--" || (field == "NA"))
throw std::runtime_error("No data provided");
return strtod(field.c_str(), NULL);
}
CountryDataTest.cpp
#include
#include
#include
#include "CountryData.h"
bool CompareGrowth(const CountryData& lhs, const CountryData& rhs)
{
return lhs.CalcGrowth() < rhs.CalcGrowth();
}
int main()
{
std::vector data = ReadCountryData("population_by_country.csv");
if (data.size() == 0)
{
std::cout << "No data read!n";
return 1;
}
auto iters = minmax_element(std::begin(data), std::end(data), CompareGrowth);
auto min_iter = iters.first;
auto max_iter = iters.second;
std::cout << max_iter->GetName()
<< " had the highest growth at "
<< max_iter->CalcGrowth()
<< " million.n";
std::cout << min_iter->GetName()
<< " had the lowest growth at "
<< min_iter->CalcGrowth()
<< " million.n";
std::string country;
while (std::getline(std::cin, country))
{
auto iter = std::find_if(std::begin(data), std::end(data),
[&country](const CountryData & c)
{
return c.GetName() == country;
});
if (iter == std::end(data))
std::cout << "There is no data for " << country << 'n';
else
std::cout << "The population of " << country << " increased by "
<< std::fixed << std::setprecision(2)
<< iter->CalcGrowth() << " million from 1980 to 2010.n";
}
}
REVISION NOTE 4/17/2020: Since are covering some material in a different order than
originally planned, more of this lab was already done for you. Every file but CountryData.cpp is
read-only, so you only need to do the TODOs in that file. The function ReadcountryData is
actually already complete. In this lab, you will implement a very simple class called CountryData
that stores some population data for a country, and (more importantly) write functions to: - parse
a line of text and convert it to a countryData object - read a file line by line and return a vector
containing all the valid data in the file The CountryData class contains three data members: - The
name of the country. - The population of the country in 1980 - The population of the country in
2010 This data will be read from a file called population_by_country.csv, each line of which
looks like this: Canada,
24.5933,24.9,25.2019,25.4563,25.7018,,32.65668,32.93596,33.2127,33.48721,33.75974 (I've
elided some data to make it fit on one line.) The data consists of fields separated by commas -
thus it's referred to as a "comma-separated values" file. (Spreadsheets can read these directly - try
it.) The first field is the name of the country, and the others are the population values in millions
from 1980 to 2010. I've provided a header file containing the declaration of the countryData
class; all you need to do is to fill in the details. The class itself should be easy; all you need to do
is: - Finish the constructor - Implement getName(), which simply returns the country name -
Implement calcGrowth0, which calculates the population growth from 1980-2010 Each of these
can actually be done in one line, though taking more than one line may help readability. The hard
part will be the two functions that actually read the data. The first is parsecountryData (), whose
signature is: CountryData parseCountryData(const std: :string & line); The line argument is one
line of the file. The function needs to split the data into separate fields (using a split () function
that I'll provide), and then return a CountryData object. The county name is the first field, the
1980 population is the second, and the 2010 population is the last. The population data will need
to be converted from std: : string to double. I've provided a function called fieldToDouble() that
recommend you use rather than writing your own. The fieldToDouble() function that I provide
will throw an exception for invalid floating-point data. The exception should NOT be caught in
parsecountryData(); see below. The second function is readCountryData(), whose signature is:
The second function is readCountryData(), whose signature is: std: : vector readCountryData
(const std: string a filename); This function needs to open the file as an ifstream, and use
getline() to read the file line by line. It should call parseCountryData() to convert this line of data
to a countryData object, and store each valid line in a vector. This vector is the return value of
the function. The call to parsecountryData( ) should be wrapped in a try block. Recall that the
syntax is: try { / call parsecountryData() // add this CountryData to the vector } catch (std:
runtime_error &e e { // ignore the error; just don't add this one to the vector In case we have not
covered exceptions by the time you do this lab, this code is provided for you. Provided functions
I've provided utilities.h and utilities. cpp which declare/define these functions: double
fieldToDouble (const std: string & field); fieldToDouble() converts the given std: : string to a
floating point value, which is returned as a double. It does some basic error checking, and throws
an exception if the field cannot be converted. std: :vector split(const std: :string & s, char sep);
split () separates the given std: : string into individual fields based on the given separator
character. The fields are returned as a vector. I've also provided Title_ratings.cpp from a
different project. You can use that as a guide for writing your parseCountryData() function.

More Related Content

Similar to CountryData.cppEDIT THIS ONE#include fstream #include str.pdf

C Programming ppt for beginners . Introduction
C Programming ppt for beginners . IntroductionC Programming ppt for beginners . Introduction
C Programming ppt for beginners . Introduction
raghukatagall2
 
(1) Learn to create class structure in C++(2) Create an array of.docx
(1) Learn to create class structure in C++(2) Create an array of.docx(1) Learn to create class structure in C++(2) Create an array of.docx
(1) Learn to create class structure in C++(2) Create an array of.docx
gertrudebellgrove
 
2 data and c
2 data and c2 data and c
2 data and c
MomenMostafa
 
Embedded C - Lecture 2
Embedded C - Lecture 2Embedded C - Lecture 2
Embedded C - Lecture 2
Mohamed Abdallah
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
Saifur Rahman
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
programming language in c&c++
programming language in c&c++programming language in c&c++
programming language in c&c++
Haripritha
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
Jan Rüegg
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
Pranali Chaudhari
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
Yaser Zhian
 
Functions
FunctionsFunctions
Functions
Swarup Boro
 
Hooking signals and dumping the callstack
Hooking signals and dumping the callstackHooking signals and dumping the callstack
Hooking signals and dumping the callstack
Thierry Gayet
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
WaheedAnwar20
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
jyothimuppasani1
 
Oops presentation
Oops presentationOops presentation
Oops presentation
sushamaGavarskar1
 
Linked list
Linked listLinked list
Linked list
somuinfo123
 
C++ Advanced
C++ AdvancedC++ Advanced
C++ AdvancedVivek Das
 

Similar to CountryData.cppEDIT THIS ONE#include fstream #include str.pdf (20)

C Programming ppt for beginners . Introduction
C Programming ppt for beginners . IntroductionC Programming ppt for beginners . Introduction
C Programming ppt for beginners . Introduction
 
(1) Learn to create class structure in C++(2) Create an array of.docx
(1) Learn to create class structure in C++(2) Create an array of.docx(1) Learn to create class structure in C++(2) Create an array of.docx
(1) Learn to create class structure in C++(2) Create an array of.docx
 
2 data and c
2 data and c2 data and c
2 data and c
 
Embedded C - Lecture 2
Embedded C - Lecture 2Embedded C - Lecture 2
Embedded C - Lecture 2
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
programming language in c&c++
programming language in c&c++programming language in c&c++
programming language in c&c++
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
COW
COWCOW
COW
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Functions
FunctionsFunctions
Functions
 
Hooking signals and dumping the callstack
Hooking signals and dumping the callstackHooking signals and dumping the callstack
Hooking signals and dumping the callstack
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Linked list
Linked listLinked list
Linked list
 
C++ Advanced
C++ AdvancedC++ Advanced
C++ Advanced
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 

More from Aggarwalelectronic18

Demonstrate cultural awareness of the Aboriginal andor Torres Strai.pdf
Demonstrate cultural awareness of the Aboriginal andor Torres Strai.pdfDemonstrate cultural awareness of the Aboriginal andor Torres Strai.pdf
Demonstrate cultural awareness of the Aboriginal andor Torres Strai.pdf
Aggarwalelectronic18
 
Deposit insuranceGroup of answer choicesleads depositors to be .pdf
Deposit insuranceGroup of answer choicesleads depositors to be .pdfDeposit insuranceGroup of answer choicesleads depositors to be .pdf
Deposit insuranceGroup of answer choicesleads depositors to be .pdf
Aggarwalelectronic18
 
Define the role of digital and social media in advertising and IBP a.pdf
Define the role of digital and social media in advertising and IBP a.pdfDefine the role of digital and social media in advertising and IBP a.pdf
Define the role of digital and social media in advertising and IBP a.pdf
Aggarwalelectronic18
 
Deep Learning for Vision Systems Given the following neural network .pdf
Deep Learning for Vision Systems Given the following neural network .pdfDeep Learning for Vision Systems Given the following neural network .pdf
Deep Learning for Vision Systems Given the following neural network .pdf
Aggarwalelectronic18
 
Debra Company began operations on June 1. The following transactions.pdf
Debra Company began operations on June 1. The following transactions.pdfDebra Company began operations on June 1. The following transactions.pdf
Debra Company began operations on June 1. The following transactions.pdf
Aggarwalelectronic18
 
De Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdf
De Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdfDe Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdf
De Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdf
Aggarwalelectronic18
 
Danone North America, un fabricante de productos l�cteos y de origen.pdf
Danone North America, un fabricante de productos l�cteos y de origen.pdfDanone North America, un fabricante de productos l�cteos y de origen.pdf
Danone North America, un fabricante de productos l�cteos y de origen.pdf
Aggarwalelectronic18
 
Curtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdf
Curtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdfCurtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdf
Curtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdf
Aggarwalelectronic18
 
Cultura y comercio el panorama internacional a las 900 horas; co.pdf
Cultura y comercio el panorama internacional a las 900 horas; co.pdfCultura y comercio el panorama internacional a las 900 horas; co.pdf
Cultura y comercio el panorama internacional a las 900 horas; co.pdf
Aggarwalelectronic18
 
Curso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdf
Curso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdfCurso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdf
Curso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdf
Aggarwalelectronic18
 
Cultural Tourism ProductsThe environmental bubble is essentially a.pdf
Cultural Tourism ProductsThe environmental bubble is essentially a.pdfCultural Tourism ProductsThe environmental bubble is essentially a.pdf
Cultural Tourism ProductsThe environmental bubble is essentially a.pdf
Aggarwalelectronic18
 
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdfCuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
Aggarwalelectronic18
 
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdfCuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
Aggarwalelectronic18
 
Create your own Wikipedia pageWikipedia is one of the backbones of.pdf
Create your own Wikipedia pageWikipedia is one of the backbones of.pdfCreate your own Wikipedia pageWikipedia is one of the backbones of.pdf
Create your own Wikipedia pageWikipedia is one of the backbones of.pdf
Aggarwalelectronic18
 
Create the tables for your final project database using Design View.pdf
Create the tables for your final project database using Design View.pdfCreate the tables for your final project database using Design View.pdf
Create the tables for your final project database using Design View.pdf
Aggarwalelectronic18
 
Create a timeline that visually details the implementation steps of .pdf
Create a timeline that visually details the implementation steps of .pdfCreate a timeline that visually details the implementation steps of .pdf
Create a timeline that visually details the implementation steps of .pdf
Aggarwalelectronic18
 
Create a UML deployment and component diagram for the scenario below.pdf
Create a UML deployment and component diagram for the scenario below.pdfCreate a UML deployment and component diagram for the scenario below.pdf
Create a UML deployment and component diagram for the scenario below.pdf
Aggarwalelectronic18
 
Create a resume for yourself 1. 1-2 Pages 2. Any of the foll.pdf
Create a resume for yourself  1. 1-2 Pages  2. Any of the foll.pdfCreate a resume for yourself  1. 1-2 Pages  2. Any of the foll.pdf
Create a resume for yourself 1. 1-2 Pages 2. Any of the foll.pdf
Aggarwalelectronic18
 
Create a GUI application in Java that allows users to chat with each.pdf
Create a GUI application in Java that allows users to chat with each.pdfCreate a GUI application in Java that allows users to chat with each.pdf
Create a GUI application in Java that allows users to chat with each.pdf
Aggarwalelectronic18
 
create a cross section for X-Y create a cross section based on.pdf
create a cross section for X-Y create a cross section based on.pdfcreate a cross section for X-Y create a cross section based on.pdf
create a cross section for X-Y create a cross section based on.pdf
Aggarwalelectronic18
 

More from Aggarwalelectronic18 (20)

Demonstrate cultural awareness of the Aboriginal andor Torres Strai.pdf
Demonstrate cultural awareness of the Aboriginal andor Torres Strai.pdfDemonstrate cultural awareness of the Aboriginal andor Torres Strai.pdf
Demonstrate cultural awareness of the Aboriginal andor Torres Strai.pdf
 
Deposit insuranceGroup of answer choicesleads depositors to be .pdf
Deposit insuranceGroup of answer choicesleads depositors to be .pdfDeposit insuranceGroup of answer choicesleads depositors to be .pdf
Deposit insuranceGroup of answer choicesleads depositors to be .pdf
 
Define the role of digital and social media in advertising and IBP a.pdf
Define the role of digital and social media in advertising and IBP a.pdfDefine the role of digital and social media in advertising and IBP a.pdf
Define the role of digital and social media in advertising and IBP a.pdf
 
Deep Learning for Vision Systems Given the following neural network .pdf
Deep Learning for Vision Systems Given the following neural network .pdfDeep Learning for Vision Systems Given the following neural network .pdf
Deep Learning for Vision Systems Given the following neural network .pdf
 
Debra Company began operations on June 1. The following transactions.pdf
Debra Company began operations on June 1. The following transactions.pdfDebra Company began operations on June 1. The following transactions.pdf
Debra Company began operations on June 1. The following transactions.pdf
 
De Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdf
De Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdfDe Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdf
De Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdf
 
Danone North America, un fabricante de productos l�cteos y de origen.pdf
Danone North America, un fabricante de productos l�cteos y de origen.pdfDanone North America, un fabricante de productos l�cteos y de origen.pdf
Danone North America, un fabricante de productos l�cteos y de origen.pdf
 
Curtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdf
Curtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdfCurtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdf
Curtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdf
 
Cultura y comercio el panorama internacional a las 900 horas; co.pdf
Cultura y comercio el panorama internacional a las 900 horas; co.pdfCultura y comercio el panorama internacional a las 900 horas; co.pdf
Cultura y comercio el panorama internacional a las 900 horas; co.pdf
 
Curso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdf
Curso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdfCurso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdf
Curso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdf
 
Cultural Tourism ProductsThe environmental bubble is essentially a.pdf
Cultural Tourism ProductsThe environmental bubble is essentially a.pdfCultural Tourism ProductsThe environmental bubble is essentially a.pdf
Cultural Tourism ProductsThe environmental bubble is essentially a.pdf
 
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdfCuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
 
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdfCuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
 
Create your own Wikipedia pageWikipedia is one of the backbones of.pdf
Create your own Wikipedia pageWikipedia is one of the backbones of.pdfCreate your own Wikipedia pageWikipedia is one of the backbones of.pdf
Create your own Wikipedia pageWikipedia is one of the backbones of.pdf
 
Create the tables for your final project database using Design View.pdf
Create the tables for your final project database using Design View.pdfCreate the tables for your final project database using Design View.pdf
Create the tables for your final project database using Design View.pdf
 
Create a timeline that visually details the implementation steps of .pdf
Create a timeline that visually details the implementation steps of .pdfCreate a timeline that visually details the implementation steps of .pdf
Create a timeline that visually details the implementation steps of .pdf
 
Create a UML deployment and component diagram for the scenario below.pdf
Create a UML deployment and component diagram for the scenario below.pdfCreate a UML deployment and component diagram for the scenario below.pdf
Create a UML deployment and component diagram for the scenario below.pdf
 
Create a resume for yourself 1. 1-2 Pages 2. Any of the foll.pdf
Create a resume for yourself  1. 1-2 Pages  2. Any of the foll.pdfCreate a resume for yourself  1. 1-2 Pages  2. Any of the foll.pdf
Create a resume for yourself 1. 1-2 Pages 2. Any of the foll.pdf
 
Create a GUI application in Java that allows users to chat with each.pdf
Create a GUI application in Java that allows users to chat with each.pdfCreate a GUI application in Java that allows users to chat with each.pdf
Create a GUI application in Java that allows users to chat with each.pdf
 
create a cross section for X-Y create a cross section based on.pdf
create a cross section for X-Y create a cross section based on.pdfcreate a cross section for X-Y create a cross section based on.pdf
create a cross section for X-Y create a cross section based on.pdf
 

Recently uploaded

2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 

Recently uploaded (20)

2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 

CountryData.cppEDIT THIS ONE#include fstream #include str.pdf

  • 1. CountryData.cpp *EDIT THIS ONE* #include #include #include "CountryData.h" #include "utilities.h" using namespace std; CountryData::CountryData(const string& n, double p1, double p2) : name(n), pop1980(p1), pop2010(p2) { } string getName() const { return name(n); } double calcGrowth() const { return (pop2010(p2) - pop1980(p1)) / pop1980(p2); } private: string name_; double pop1980(p1); double pop2010(p2); } double fieldToDouble(const string& field) { try { return stod(field); } catch (...) { throw runtime_error("invalid floating-point field: " + field); } } vector split(const string& s, char sep) { vector fields; stringstream ss(s); string field; while (getline(ss, field, sep)) {
  • 2. fields.push_back(field); } return fields; } CountryData parseCountryData(const string& line) { vector fields = split(line, ','); if (fields.size() != 12) { throw runtime_error("invalid line: " + line); } string name = fields[0]; double pop1980 = fieldToDouble(fields[1]); double pop2010 = fieldToDouble(fields[11]); return CountryData(name, pop1980, pop2010); } vector readCountryData(const string& filename) { vector countryDataList; ifstream infile(filename); if (!infile) { throw runtime_error("unable to open file: " + filename); } string line; while (getline(infile, line)) { try { CountryData countryData = parseCountryData(line); countryDataList.push_back(countryData); } catch (const runtime_error&) { // ignore the error; just don't add this one to the vector } } return countryDataList; } vector ReadCountryData(const string & filename) { vector data; ifstream ifs{ filename };
  • 3. string line; // Read the header line getline(ifs, line); while (getline(ifs, line)) { try { CountryData cd = ParseCountryData(line); data.push_back(cd); } catch (runtime_error & e) { string error{ e.what() }; } } return data; } CountrtyData.h #pragma once #include #include class CountryData { public: CountryData(const std::string & n, double p1, double p2); std::string GetName() const; double CalcGrowth() const; private: std::string name; double pop1980; double pop2010; }; CountryData ParseCountryData(const std::string& line); std::vector ReadCountryData(const std::string& filename); utilities.h #pragma once
  • 4. #include #include // Split a string into sub-strings based on the given // delimiter. For example, if the input is // // Ron,Ginny,George,Fred,Percy,Bill,Charlie // // the output is a 7-element vector with // the following entries: // // [0] = "Ron" // [1] = "Ginny" // [2] = "George" // [3] = "Fred" // [4] = "Percy" // [5] = "Bill" // [6] = "Charlie" // std::vector split(const std::string& s, char seperator); // Converts a database field string to an integer. // If the field cannot be converted to an int, // a runtime_error exception is thrown. int fieldToInt(const std::string & field); // Converts a database field to a double. // If the field cannot be converted to an double, // a runtime_error exception is thrown. double fieldToDouble(const std::string & field); utilities.cpp #include #include #include "utilities.h" std::vector split(const std::string & s, char sep) { std::vector fields; size_t i = 0;
  • 5. size_t len = s.length(); while (i < len) { // Skip characters until we find a separator. size_t j = i; while ((i < len) && (s[i] != sep)) i++; // Add this field - which may be empty! - to the output. if (j == i) fields.emplace_back(); else fields.emplace_back(&s[j], i - j); // Skip past the separator. i++; // If this put us at the end of the string, // we need to account for the blank field at // the end. if (i == len) fields.emplace_back(); } return fields; } int fieldToInt(const std::string & field) { if (field.length() == 0) throw std::runtime_error("Cannot convert 0-length string"); if (field == "--" || (field == "NA")) throw std::runtime_error("No data provided"); return strtol(field.c_str(), NULL, 10); } double fieldToDouble(const std::string & field) { if (field.length() == 0) throw std::runtime_error("Cannot convert 0-length string"); if (field == "--" || (field == "NA")) throw std::runtime_error("No data provided"); return strtod(field.c_str(), NULL);
  • 6. } CountryDataTest.cpp #include #include #include #include "CountryData.h" bool CompareGrowth(const CountryData& lhs, const CountryData& rhs) { return lhs.CalcGrowth() < rhs.CalcGrowth(); } int main() { std::vector data = ReadCountryData("population_by_country.csv"); if (data.size() == 0) { std::cout << "No data read!n"; return 1; } auto iters = minmax_element(std::begin(data), std::end(data), CompareGrowth); auto min_iter = iters.first; auto max_iter = iters.second; std::cout << max_iter->GetName() << " had the highest growth at " << max_iter->CalcGrowth() << " million.n"; std::cout << min_iter->GetName() << " had the lowest growth at " << min_iter->CalcGrowth() << " million.n"; std::string country; while (std::getline(std::cin, country)) { auto iter = std::find_if(std::begin(data), std::end(data), [&country](const CountryData & c) {
  • 7. return c.GetName() == country; }); if (iter == std::end(data)) std::cout << "There is no data for " << country << 'n'; else std::cout << "The population of " << country << " increased by " << std::fixed << std::setprecision(2) << iter->CalcGrowth() << " million from 1980 to 2010.n"; } } REVISION NOTE 4/17/2020: Since are covering some material in a different order than originally planned, more of this lab was already done for you. Every file but CountryData.cpp is read-only, so you only need to do the TODOs in that file. The function ReadcountryData is actually already complete. In this lab, you will implement a very simple class called CountryData that stores some population data for a country, and (more importantly) write functions to: - parse a line of text and convert it to a countryData object - read a file line by line and return a vector containing all the valid data in the file The CountryData class contains three data members: - The name of the country. - The population of the country in 1980 - The population of the country in 2010 This data will be read from a file called population_by_country.csv, each line of which looks like this: Canada, 24.5933,24.9,25.2019,25.4563,25.7018,,32.65668,32.93596,33.2127,33.48721,33.75974 (I've elided some data to make it fit on one line.) The data consists of fields separated by commas - thus it's referred to as a "comma-separated values" file. (Spreadsheets can read these directly - try it.) The first field is the name of the country, and the others are the population values in millions from 1980 to 2010. I've provided a header file containing the declaration of the countryData class; all you need to do is to fill in the details. The class itself should be easy; all you need to do is: - Finish the constructor - Implement getName(), which simply returns the country name - Implement calcGrowth0, which calculates the population growth from 1980-2010 Each of these can actually be done in one line, though taking more than one line may help readability. The hard part will be the two functions that actually read the data. The first is parsecountryData (), whose signature is: CountryData parseCountryData(const std: :string & line); The line argument is one line of the file. The function needs to split the data into separate fields (using a split () function that I'll provide), and then return a CountryData object. The county name is the first field, the
  • 8. 1980 population is the second, and the 2010 population is the last. The population data will need to be converted from std: : string to double. I've provided a function called fieldToDouble() that recommend you use rather than writing your own. The fieldToDouble() function that I provide will throw an exception for invalid floating-point data. The exception should NOT be caught in parsecountryData(); see below. The second function is readCountryData(), whose signature is: The second function is readCountryData(), whose signature is: std: : vector readCountryData (const std: string a filename); This function needs to open the file as an ifstream, and use getline() to read the file line by line. It should call parseCountryData() to convert this line of data to a countryData object, and store each valid line in a vector. This vector is the return value of the function. The call to parsecountryData( ) should be wrapped in a try block. Recall that the syntax is: try { / call parsecountryData() // add this CountryData to the vector } catch (std: runtime_error &e e { // ignore the error; just don't add this one to the vector In case we have not covered exceptions by the time you do this lab, this code is provided for you. Provided functions I've provided utilities.h and utilities. cpp which declare/define these functions: double fieldToDouble (const std: string & field); fieldToDouble() converts the given std: : string to a floating point value, which is returned as a double. It does some basic error checking, and throws an exception if the field cannot be converted. std: :vector split(const std: :string & s, char sep); split () separates the given std: : string into individual fields based on the given separator character. The fields are returned as a vector. I've also provided Title_ratings.cpp from a different project. You can use that as a guide for writing your parseCountryData() function.