SlideShare a Scribd company logo
1 of 8
Download to read offline
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 . Introductionraghukatagall2
 
(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.docxgertrudebellgrove
 
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.pptxJawadTanvir
 
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 FeaturesJan Rüegg
 
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.0Yaser Zhian
 
Hooking signals and dumping the callstack
Hooking signals and dumping the callstackHooking signals and dumping the callstack
Hooking signals and dumping the callstackThierry Gayet
 
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 .pdfjyothimuppasani1
 
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.pdfAggarwalelectronic18
 
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 .pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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 .pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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 .pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 
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.pdfAggarwalelectronic18
 

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

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Recently uploaded (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

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.